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

📄 validatorfactory.java

📁 在Struts2中的jar包xwork的源代码.版本为2.0.7
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
 * replaced with the evaluated value of the string between the ${ and }. This * allows you to parameterize your messages with values from the validator, the * Action, or both. </p> * <p/> * <p><b>NOTE:</b>Since validation rules are in an XML file, you must make sure * you escape special characters. For example, notice that in the expression * validator rule above we use "&gt;" instead of ">". Consult a resource on XML * for the full list of characters that must be escaped. The most commonly used * characters that must be escaped are: & (use &amp;), > (user &gt;), and < (use &lt;).</p> * <p/> * <p>Here is an example of a parameterized message:</p> * <p>This will pull the min and max parameters from the IntRangeFieldValidator and * the value of bar from the Action.</p> * <!-- END SNIPPET: validationRules3 --> * <p/> * <pre> * <!-- START SNIPPET: exValidationRules3 --> *    bar must be between ${min} and ${max}, current value is ${bar}. * <!-- END SNIPPET: exValidationRules3 --> * </pre> * * @author Jason Carreira * @author James House * @version $Date: 2008-11-15 14:12:31 +0100 (Sat, 15 Nov 2008) $ $Id: ValidatorFactory.java 1870 2008-11-15 13:12:31Z rainerh $ */public class ValidatorFactory {    private static Map validators = new HashMap();    private static Log LOG = LogFactory.getLog(ValidatorFactory.class);    static {        parseValidators();    }    private ValidatorFactory() {    }    /**     * Get a Validator that matches the given configuration.     *     * @param cfg the configurator.     * @return the validator.     * @deprecated     */    public static Validator getValidator(ValidatorConfig cfg) {        return getValidator(cfg, ObjectFactory.getObjectFactory());    }    /**     * Get a Validator that matches the given configuration.     *     * @param cfg the configurator.     * @return the validator.     */    public static Validator getValidator(ValidatorConfig cfg, ObjectFactory objectFactory) {        String className = lookupRegisteredValidatorType(cfg.getType());        Validator validator;        try {            // instantiate the validator, and set configured parameters            //todo - can this use the ThreadLocal?            validator = objectFactory.buildValidator(className, cfg.getParams(), null); // ActionContext.getContext().getContextMap());        } catch (Exception e) {            final String msg = "There was a problem creating a Validator of type " + className + " : caused by " + e.getMessage();            throw new XWorkException(msg, e, cfg);        }        // set other configured properties        validator.setMessageKey(cfg.getMessageKey());        validator.setDefaultMessage(cfg.getDefaultMessage());        if (validator instanceof ShortCircuitableValidator) {            ((ShortCircuitableValidator) validator).setShortCircuit(cfg.isShortCircuit());        }        return validator;    }    /**     * Registers the given validator to the existing map of validators.     * This will <b>add</b> to the existing list.     *     * @param name      name of validator to add.     * @param className the FQ classname of the validator.     */    public static void registerValidator(String name, String className) {        if (LOG.isDebugEnabled()) {            LOG.debug("Registering validator of class " + className + " with name " + name);        }        validators.put(name, className);    }    /**     * Lookup to get the FQ classname of the given validator name.     *     * @param name name of validator to lookup.     * @return the found FQ classname     * @throws IllegalArgumentException is thrown if the name is not found.     */    public static String lookupRegisteredValidatorType(String name) {        // lookup the validator class mapped to the type name        String className = (String) validators.get(name);        if (className == null) {            throw new IllegalArgumentException("There is no validator class mapped to the name " + name);        }        return className;    }    private static void parseValidators() {        if (LOG.isDebugEnabled()) {            LOG.debug("Loading validator definitions.");        }        // Get custom validator configurations via the classpath        List<File> files = new ArrayList<File>();        try {            Iterator<URL> urls = ClassLoaderUtil.getResources("", ValidatorFactory.class, false);            while (urls.hasNext()) {                URL u = urls.next();                try {                    URI uri = new URI(u.toExternalForm().replaceAll(" ", "%20"));                    if ("file".equalsIgnoreCase(uri.getScheme())) {                        File f = new File(uri);                        FilenameFilter filter = new FilenameFilter() {                            public boolean accept(File file, String fileName) {                                return fileName.contains("-validators.xml");                            }                        };                        // First check if this is a directory                        // If yes, then just do a "list" to get all files in this directory                        // and match the filenames with *-validators.xml. If the filename                        // matches then add to the list of files to be parsed                        if (f.isDirectory()) {                            files.addAll(Arrays.asList(f.listFiles(filter)));                        } else {                            // If this is not a directory, then get hold of the inputstream.                            // If its not a ZipInputStream, then create a ZipInputStream out                            // of it. The intention is to allow nested jar files to be scanned                            // for *-validators.xml.                            // Ex: struts-app.jar -> MyApp.jar -> Login-validators.xml should be                            // parsed and loaded.                            ZipInputStream zipInputStream = null;                            try {                                InputStream inputStream = u.openStream();                                if (inputStream instanceof ZipInputStream) {                                    zipInputStream = (ZipInputStream) inputStream;                                } else {                                    zipInputStream = new ZipInputStream(inputStream);                                }                                ZipEntry zipEntry = zipInputStream.getNextEntry();                                while (zipEntry != null) {                                    if (zipEntry.getName().endsWith("-validators.xml")) {                                        if (LOG.isTraceEnabled()) {                                            LOG.trace("Adding validator " + zipEntry.getName());                                        }                                        files.add(new File(zipEntry.getName()));                                    }                                    zipEntry = zipInputStream.getNextEntry();                                }                            } finally {                                //cleanup                                if (zipInputStream != null) {                                    zipInputStream.close();                                }                            }                        }                    }                } catch (Exception ex) {                    LOG.error("Unable to load " + u.toString(), ex);                }            }        } catch (IOException e) {            throw new ConfigurationException("Unable to load validator files", e);        }        // Parse default validator configurations        String resourceName = "com/opensymphony/xwork2/validator/validators/default.xml";        retrieveValidatorConfiguration(resourceName);        // Overwrite and extend defaults with application specific validator configurations        resourceName = "validators.xml";        retrieveValidatorConfiguration(resourceName);        // Add custom (plugin) specific validator configurations        for (File file : files) {            retrieveValidatorConfiguration(file.getName());        }    }    private static void retrieveValidatorConfiguration(String resourceName) {        InputStream is = ClassLoaderUtil.getResourceAsStream(resourceName, ValidatorFactory.class);        if (is != null) {            ValidatorFileParser.parseValidatorDefinitions(is, resourceName);        }    }}

⌨️ 快捷键说明

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