⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 validatoraction.java

📁 java验证框架 java验证框架
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

    /**
     * Read a javascript function from a file.
     * @param javascriptFileName The file containing the javascript.
     * @return The javascript function or null if it could not be loaded.
     */
    private String readJavascriptFile(String javascriptFileName) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = this.getClass().getClassLoader();
        }

        InputStream is = classLoader.getResourceAsStream(javascriptFileName);
        if (is == null) {
            is = this.getClass().getResourceAsStream(javascriptFileName);
        }

        if (is == null) {
            getLog().debug("  Unable to read javascript name "+javascriptFileName);
            return null;
        }

        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        try {
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

        } catch(IOException e) {
            getLog().error("Error reading javascript file.", e);

        } finally {
            try {
                reader.close();
            } catch(IOException e) {
                getLog().error("Error closing stream to javascript file.", e);
            }
        }
        
        String function = buffer.toString();
        return function.equals("") ? null : function;
    }

    /**
     * @return A filename suitable for passing to a 
     * ClassLoader.getResourceAsStream() method.
     */
    private String formatJavascriptFileName() {
        String name = this.jsFunction.substring(1);

        if (!this.jsFunction.startsWith("/")) {
            name = jsFunction.replace('.', '/') + ".js";
        }

        return name;
    }

    /**
     * @return true if the javascript for this action has already been loaded.
     */
    private boolean javascriptAlreadyLoaded() {
        return (this.javascript != null);
    }

    /**
     * Used to generate the javascript name when it is not specified.
     */
    private String generateJsFunction() {
        StringBuffer jsName =
                new StringBuffer("org.apache.commons.validator.javascript");

        jsName.append(".validate");
        jsName.append(name.substring(0, 1).toUpperCase());
        jsName.append(name.substring(1, name.length()));

        return jsName.toString();
    }

    /**
     * Checks whether or not the value passed in is in the depends field.
     * @param validatorName Name of the dependency to check.
     * @return Whether the named validator is a dependant.
     */
    public boolean isDependency(String validatorName) {
        return this.dependencyList.contains(validatorName);
    }

    /**
     * Returns the dependent validator names as an unmodifiable
     * <code>List</code>.
     * @return List of the validator action's depedents.
     */
    public List getDependencyList() {
        return Collections.unmodifiableList(this.dependencyList);
    }

    /**
     * Returns a string representation of the object.
     * @return a string representation.
     */
    public String toString() {
        StringBuffer results = new StringBuffer("ValidatorAction: ");
        results.append(name);
        results.append("\n");

        return results.toString();
    }
    
    /**
     * Dynamically runs the validation method for this validator and returns 
     * true if the data is valid.
     * @param field
     * @param params A Map of class names to parameter values.
     * @param results
     * @param pos The index of the list property to validate if it's indexed.
     * @throws ValidatorException
     */
    boolean executeValidationMethod(
        Field field,
        Map params,
        ValidatorResults results,
        int pos)
        throws ValidatorException {

        params.put(Validator.VALIDATOR_ACTION_PARAM, this);

        try {
            if (this.validationMethod == null) {
                synchronized(this) {
                    ClassLoader loader = this.getClassLoader(params);
                    this.loadValidationClass(loader);
                    this.loadParameterClasses(loader);
                    this.loadValidationMethod();
                }
            }

            Object[] paramValues = this.getParameterValues(params);
            
            if (field.isIndexed()) {
                this.handleIndexedField(field, pos, paramValues);
            }

            Object result = null;
            try {
                result =
                    validationMethod.invoke(
                        getValidationClassInstance(),
                        paramValues);

            } catch (IllegalArgumentException e) {
                throw new ValidatorException(e.getMessage());
            } catch (IllegalAccessException e) {
                throw new ValidatorException(e.getMessage());
            } catch (InvocationTargetException e) {

                if (e.getTargetException() instanceof Exception) {
                    throw (Exception) e.getTargetException();

                } else if (e.getTargetException() instanceof Error) {
                    throw (Error) e.getTargetException();
                }
            }

            boolean valid = this.isValid(result);
            if (!valid || (valid && !onlyReturnErrors(params))) {
                results.add(field, this.name, valid, result);
            }

            if (!valid) {
                return false;
            }

            // TODO This catch block remains for backward compatibility.  Remove
            // this for Validator 2.0 when exception scheme changes.
        } catch (Exception e) {
            if (e instanceof ValidatorException) {
                throw (ValidatorException) e;
            }

            getLog().error(
                "Unhandled exception thrown during validation: " + e.getMessage(),
                e);

            results.add(field, this.name, false);
            return false;
        }

        return true;
    }
    
    /**
     * Load the Method object for the configured validation method name.
     * @throws ValidatorException
     */
    private void loadValidationMethod() throws ValidatorException {
        if (this.validationMethod != null) {
            return;
        }
     
        try {
            this.validationMethod =
                this.validationClass.getMethod(this.method, this.parameterClasses);
     
        } catch (NoSuchMethodException e) {
            throw new ValidatorException("No such validation method: " + 
                e.getMessage());
        }
    }
    
    /**
     * Load the Class object for the configured validation class name.
     * @param loader The ClassLoader used to load the Class object.
     * @throws ValidatorException
     */
    private void loadValidationClass(ClassLoader loader) 
        throws ValidatorException {
        
        if (this.validationClass != null) {
            return;
        }
        
        try {
            this.validationClass = loader.loadClass(this.classname);
        } catch (ClassNotFoundException e) {
            throw new ValidatorException(e.toString());
        }
    }
    
    /**
     * Converts a List of parameter class names into their Class objects.
     * @return An array containing the Class object for each parameter.  This 
     * array is in the same order as the given List and is suitable for passing 
     * to the validation method.
     * @throws ValidatorException if a class cannot be loaded.
     */
    private void loadParameterClasses(ClassLoader loader)
        throws ValidatorException {

        if (this.parameterClasses != null) {
            return;
        }
        
        Class[] parameterClasses = new Class[this.methodParameterList.size()];

        for (int i = 0; i < this.methodParameterList.size(); i++) {
            String paramClassName = (String) this.methodParameterList.get(i);

            try {
                parameterClasses[i] = loader.loadClass(paramClassName);
                    
            } catch (ClassNotFoundException e) {
                throw new ValidatorException(e.getMessage());
            }
        }

        this.parameterClasses = parameterClasses;
    }
    
    /**
     * Converts a List of parameter class names into their values contained in 
     * the parameters Map.
     * @param params A Map of class names to parameter values.
     * @return An array containing the value object for each parameter.  This 
     * array is in the same order as the given List and is suitable for passing 
     * to the validation method.
     */
    private Object[] getParameterValues(Map params) {

        Object[] paramValue = new Object[this.methodParameterList.size()];

        for (int i = 0; i < this.methodParameterList.size(); i++) {
            String paramClassName = (String) this.methodParameterList.get(i);
            paramValue[i] = params.get(paramClassName);
        }

        return paramValue;
    }
    
    /**
     * Return an instance of the validation class or null if the validation 
     * method is static so does not require an instance to be executed.
     */
    private Object getValidationClassInstance() throws ValidatorException {
        if (Modifier.isStatic(this.validationMethod.getModifiers())) {
            this.instance = null;

        } else {
            if (this.instance == null) {
                try {
                    this.instance = this.validationClass.newInstance();
                } catch (InstantiationException e) {
                    String msg =
                        "Couldn't create instance of "
                            + this.classname
                            + ".  "
                            + e.getMessage();

                    throw new ValidatorException(msg);

                } catch (IllegalAccessException e) {
                    String msg =
                        "Couldn't create instance of "
                            + this.classname
                            + ".  "
                            + e.getMessage();

                    throw new ValidatorException(msg);
                }
            }
        }

        return this.instance;
    }
    
    /**
     * Modifies the paramValue array with indexed fields.
     *
     * @param field
     * @param pos
     * @param paramValues
     */
    private void handleIndexedField(Field field, int pos, Object[] paramValues)
        throws ValidatorException {

        int beanIndex = this.methodParameterList.indexOf(Validator.BEAN_PARAM);
        int fieldIndex = this.methodParameterList.indexOf(Validator.FIELD_PARAM);

        Object indexedList[] = field.getIndexedProperty(paramValues[beanIndex]);

        // Set current iteration object to the parameter array
        paramValues[beanIndex] = indexedList[pos];

        // Set field clone with the key modified to represent
        // the current field
        Field indexedField = (Field) field.clone();
        indexedField.setKey(
            ValidatorUtils.replace(
                indexedField.getKey(),
                Field.TOKEN_INDEXED,
                "[" + pos + "]"));

        paramValues[fieldIndex] = indexedField;
    }
    
    /**
     * If the result object is a <code>Boolean</code>, it will return its 
     * value.  If not it will return <code>false</code> if the object is 
     * <code>null</code> and <code>true</code> if it isn't.
     */
    private boolean isValid(Object result) {
        if (result instanceof Boolean) {
            Boolean valid = (Boolean) result;
            return valid.booleanValue();
        } else {
            return (result != null);
        }
    }

    /**
     * Returns the ClassLoader set in the Validator contained in the parameter
     * Map.
     */
    private ClassLoader getClassLoader(Map params) {
        Validator v = (Validator) params.get(Validator.VALIDATOR_PARAM);
        return v.getClassLoader();
    }
    
    /**
     * Returns the onlyReturnErrors setting in the Validator contained in the 
     * parameter Map.
     */
    private boolean onlyReturnErrors(Map params) {
        Validator v = (Validator) params.get(Validator.VALIDATOR_PARAM);
        return v.getOnlyReturnErrors();
    }

    /**
     * Accessor method for Log instance.
     *
     * The Log instance variable is transient and
     * accessing it through this method ensures it
     * is re-initialized when this instance is
     * de-serialized.
     *
     * @return The Log instance.
     */
    private Log getLog() {
        if (log == null) {
            log =  LogFactory.getLog(ValidatorAction.class);
        }
        return log;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -