You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by lu...@apache.org on 2008/06/18 03:40:00 UTC
svn commit: r669047 [1/2] - in /myfaces/commons/trunk:
myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/
myfaces-commons-validators/src/main/conf/
myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/
myfaces...
Author: lu4242
Date: Tue Jun 17 18:39:59 2008
New Revision: 669047
URL: http://svn.apache.org/viewvc?rev=669047&view=rev
Log:
move tomahawk converters and validators to commons
Added:
myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/
myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ValidatorBaseTag.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/myfaces/
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/myfaces/commons/
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/myfaces/commons/validator/
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/myfaces/commons/validator/AbstractValidatorTestCase.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/myfaces/commons/validator/EmailValidatorTestCase.java (with props)
myfaces/commons/trunk/myfaces-commons-validators/src/test/java/org/apache/myfaces/commons/validator/RegExprValidatorTestCase.java (with props)
Added: myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java (added)
+++ myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,353 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.faces.FacesException;
+import javax.faces.context.FacesContext;
+import javax.el.ExpressionFactory;
+import java.io.InputStream;
+import java.io.IOException;
+import java.lang.reflect.Array;
+import java.util.*;
+
+
+/**
+ * @author Manfred Geiler (latest modification by $Author$)
+ * @author Anton Koinov
+ * @version $Revision$ $Date$
+ */
+public final class ClassUtils
+{
+ //~ Static fields/initializers -----------------------------------------------------------------
+
+ private static final Log log = LogFactory.getLog(ClassUtils.class);
+
+ public static final Class BOOLEAN_ARRAY_CLASS = boolean[].class;
+ public static final Class BYTE_ARRAY_CLASS = byte[].class;
+ public static final Class CHAR_ARRAY_CLASS = char[].class;
+ public static final Class SHORT_ARRAY_CLASS = short[].class;
+ public static final Class INT_ARRAY_CLASS = int[].class;
+ public static final Class LONG_ARRAY_CLASS = long[].class;
+ public static final Class FLOAT_ARRAY_CLASS = float[].class;
+ public static final Class DOUBLE_ARRAY_CLASS = double[].class;
+ public static final Class OBJECT_ARRAY_CLASS = Object[].class;
+ public static final Class BOOLEAN_OBJECT_ARRAY_CLASS = Boolean[].class;
+ public static final Class BYTE_OBJECT_ARRAY_CLASS = Byte[].class;
+ public static final Class CHARACTER_OBJECT_ARRAY_CLASS = Character[].class;
+ public static final Class SHORT_OBJECT_ARRAY_CLASS = Short[].class;
+ public static final Class INTEGER_OBJECT_ARRAY_CLASS = Integer[].class;
+ public static final Class LONG_OBJECT_ARRAY_CLASS = Long[].class;
+ public static final Class FLOAT_OBJECT_ARRAY_CLASS = Float[].class;
+ public static final Class DOUBLE_OBJECT_ARRAY_CLASS = Double[].class;
+ public static final Class STRING_OBJECT_ARRAY_CLASS = String[].class;
+
+ public static final Map COMMON_TYPES = new HashMap(64);
+ static
+ {
+ COMMON_TYPES.put("byte", Byte.TYPE);
+ COMMON_TYPES.put("char", Character.TYPE);
+ COMMON_TYPES.put("double", Double.TYPE);
+ COMMON_TYPES.put("float", Float.TYPE);
+ COMMON_TYPES.put("int", Integer.TYPE);
+ COMMON_TYPES.put("long", Long.TYPE);
+ COMMON_TYPES.put("short", Short.TYPE);
+ COMMON_TYPES.put("boolean", Boolean.TYPE);
+ COMMON_TYPES.put("void", Void.TYPE);
+ COMMON_TYPES.put("java.lang.Object", Object.class);
+ COMMON_TYPES.put("java.lang.Boolean", Boolean.class);
+ COMMON_TYPES.put("java.lang.Byte", Byte.class);
+ COMMON_TYPES.put("java.lang.Character", Character.class);
+ COMMON_TYPES.put("java.lang.Short", Short.class);
+ COMMON_TYPES.put("java.lang.Integer", Integer.class);
+ COMMON_TYPES.put("java.lang.Long", Long.class);
+ COMMON_TYPES.put("java.lang.Float", Float.class);
+ COMMON_TYPES.put("java.lang.Double", Double.class);
+ COMMON_TYPES.put("java.lang.String", String.class);
+
+ COMMON_TYPES.put("byte[]", BYTE_ARRAY_CLASS);
+ COMMON_TYPES.put("char[]", CHAR_ARRAY_CLASS);
+ COMMON_TYPES.put("double[]", DOUBLE_ARRAY_CLASS);
+ COMMON_TYPES.put("float[]", FLOAT_ARRAY_CLASS);
+ COMMON_TYPES.put("int[]", INT_ARRAY_CLASS);
+ COMMON_TYPES.put("long[]", LONG_ARRAY_CLASS);
+ COMMON_TYPES.put("short[]", SHORT_ARRAY_CLASS);
+ COMMON_TYPES.put("boolean[]", BOOLEAN_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Object[]", OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Boolean[]", BOOLEAN_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Byte[]", BYTE_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Character[]", CHARACTER_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Short[]", SHORT_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Integer[]", INTEGER_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Long[]", LONG_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Float[]", FLOAT_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.Double[]", DOUBLE_OBJECT_ARRAY_CLASS);
+ COMMON_TYPES.put("java.lang.String[]", STRING_OBJECT_ARRAY_CLASS);
+ // array of void is not a valid type
+ }
+
+ /** utility class, do not instantiate */
+ private ClassUtils()
+ {
+ // utility class, disable instantiation
+ }
+
+ //~ Methods ------------------------------------------------------------------------------------
+
+ /**
+ * Tries a Class.loadClass with the context class loader of the current thread first and
+ * automatically falls back to the ClassUtils class loader (i.e. the loader of the
+ * myfaces.jar lib) if necessary.
+ *
+ * @param type fully qualified name of a non-primitive non-array class
+ * @return the corresponding Class
+ * @throws NullPointerException if type is null
+ * @throws ClassNotFoundException
+ */
+ public static Class classForName(String type)
+ throws ClassNotFoundException
+ {
+ if (type == null) throw new NullPointerException("type");
+ try
+ {
+ // Try WebApp ClassLoader first
+ return Class.forName(type,
+ false, // do not initialize for faster startup
+ Thread.currentThread().getContextClassLoader());
+ }
+ catch (ClassNotFoundException ignore)
+ {
+ // fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib)
+ return Class.forName(type,
+ false, // do not initialize for faster startup
+ ClassUtils.class.getClassLoader());
+ }
+ }
+
+
+ /**
+ * Same as {@link #classForName(String)}, but throws a RuntimeException
+ * (FacesException) instead of a ClassNotFoundException.
+ *
+ * @return the corresponding Class
+ * @throws NullPointerException if type is null
+ * @throws FacesException if class not found
+ */
+ public static Class simpleClassForName(String type)
+ {
+ try
+ {
+ return classForName(type);
+ }
+ catch (ClassNotFoundException e)
+ {
+ log.error("Class " + type + " not found", e);
+ throw new FacesException(e);
+ }
+ }
+
+
+ /**
+ * Similar as {@link #classForName(String)}, but also supports primitive types
+ * and arrays as specified for the JavaType element in the JavaServer Faces Config DTD.
+ *
+ * @param type fully qualified class name or name of a primitive type, both optionally
+ * followed by "[]" to indicate an array type
+ * @return the corresponding Class
+ * @throws NullPointerException if type is null
+ * @throws ClassNotFoundException
+ */
+ public static Class javaTypeToClass(String type)
+ throws ClassNotFoundException
+ {
+ if (type == null) throw new NullPointerException("type");
+
+ // try common types and arrays of common types first
+ Class clazz = (Class) COMMON_TYPES.get(type);
+ if (clazz != null)
+ {
+ return clazz;
+ }
+
+ int len = type.length();
+ if (len > 2 && type.charAt(len - 1) == ']' && type.charAt(len - 2) == '[')
+ {
+ String componentType = type.substring(0, len - 2);
+ Class componentTypeClass = classForName(componentType);
+ return Array.newInstance(componentTypeClass, 0).getClass();
+ }
+
+ return classForName(type);
+
+ }
+
+
+ /**
+ * Same as {@link #javaTypeToClass(String)}, but throws a RuntimeException
+ * (FacesException) instead of a ClassNotFoundException.
+ *
+ * @return the corresponding Class
+ * @throws NullPointerException if type is null
+ * @throws FacesException if class not found
+ */
+ public static Class simpleJavaTypeToClass(String type)
+ {
+ try
+ {
+ return javaTypeToClass(type);
+ }
+ catch (ClassNotFoundException e)
+ {
+ log.error("Class " + type + " not found", e);
+ throw new FacesException(e);
+ }
+ }
+
+ public static InputStream getResourceAsStream(String resource)
+ {
+ InputStream stream = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(resource);
+ if (stream == null)
+ {
+ // fallback
+ stream = ClassUtils.class.getClassLoader().getResourceAsStream(resource);
+ }
+ return stream;
+ }
+
+ /**
+ * @param resource Name of resource(s) to find in classpath
+ * @param defaultObject The default object to use to determine the class loader (if none associated with current thread.)
+ * @return Iterator over URL Objects
+ */
+ public static Iterator getResources(String resource, Object defaultObject)
+ {
+ try
+ {
+ Enumeration resources = getCurrentLoader(defaultObject).getResources(resource);
+ List lst = new ArrayList();
+ while (resources.hasMoreElements())
+ {
+ lst.add(resources.nextElement());
+ }
+ return lst.iterator();
+ }
+ catch (IOException e)
+ {
+ log.error(e.getMessage(), e);
+ throw new FacesException(e);
+ }
+ }
+
+
+ public static Object newInstance(String type)
+ throws FacesException
+ {
+ if (type == null) return null;
+ return newInstance(simpleClassForName(type));
+ }
+
+ public static Object newInstance(String type, Class expectedType) throws FacesException
+ {
+ return newInstance(type, expectedType == null ? null : new Class[] {expectedType});
+ }
+
+ public static Object newInstance(String type, Class[] expectedTypes)
+ {
+ if (type == null)
+ return null;
+
+ Class clazzForName = simpleClassForName(type);
+
+ if(expectedTypes != null)
+ {
+ for (int i = 0, size = expectedTypes.length; i < size; i++)
+ {
+ if (!expectedTypes[i].isAssignableFrom(clazzForName))
+ {
+ throw new FacesException("'" + type + "' does not implement expected type '" + expectedTypes[i]
+ + "'");
+ }
+ }
+ }
+
+ return newInstance(clazzForName);
+ }
+
+ public static Object newInstance(Class clazz)
+ throws FacesException
+ {
+ try
+ {
+ return clazz.newInstance();
+ }
+ catch(NoClassDefFoundError e)
+ {
+ log.error("Class : "+clazz.getName()+" not found.",e);
+ throw new FacesException(e);
+ }
+ catch (InstantiationException e)
+ {
+ log.error(e.getMessage(), e);
+ throw new FacesException(e);
+ }
+ catch (IllegalAccessException e)
+ {
+ log.error(e.getMessage(), e);
+ throw new FacesException(e);
+ }
+ }
+
+ public static Object convertToType(Object value, Class desiredClass)
+ {
+ if (value == null) return null;
+
+ try
+ {
+ ExpressionFactory expFactory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
+ return expFactory.coerceToType(value, desiredClass);
+ }
+ catch (Exception e)
+ {
+ String message = "Cannot coerce " + value.getClass().getName()
+ + " to " + desiredClass.getName();
+ log.error(message, e);
+ throw new FacesException(message, e);
+ }
+ }
+
+ /**
+ * Gets the ClassLoader associated with the current thread. Returns the class loader associated with
+ * the specified default object if no context loader is associated with the current thread.
+ *
+ * @param defaultObject The default object to use to determine the class loader (if none associated with current thread.)
+ * @return ClassLoader
+ */
+ protected static ClassLoader getCurrentLoader(Object defaultObject)
+ {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ if(loader == null)
+ {
+ loader = defaultObject.getClass().getClassLoader();
+ }
+ return loader;
+ }
+}
Propchange: myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-utils/src/main/java/org/apache/myfaces/commons/util/ClassUtils.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml Tue Jun 17 18:39:59 2008
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+-->
+<!DOCTYPE facelet-taglib
+ PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
+<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet">
+
+</facelet-taglib>
\ No newline at end of file
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/facelets-taglib-base.xml
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml Tue Jun 17 18:39:59 2008
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+-->
+
+<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
+ version="1.2">
+
+</faces-config>
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/faces-config-base.xml
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld Tue Jun 17 18:39:59 2008
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+-->
+<taglib xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
+ version="2.1">
+
+</taglib>
\ No newline at end of file
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/conf/mcv-base.tld
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import java.util.regex.PatternSyntaxException;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.validator.Validator;
+import javax.faces.validator.ValidatorException;
+
+import org.apache.myfaces.commons.util.MessageUtils;
+
+/**
+ * Validation by validating comma separated values individually.
+ *
+ * @JSFValidator
+ * name = "mcv:validateCSV"
+ * class = "org.apache.myfaces.commons.validator.CSVValidator"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateCSVTag"
+ * serialuidtag = "-8874279182242196266L"
+ *
+ * @author Lance Frohman
+ *
+ * @version $Revision$ $Date$
+ */
+public abstract class AbstractCSVValidator extends ValidatorBase {
+ /**
+ * <p>The standard converter id for this converter.</p>
+ */
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.csv";
+ /**
+ * <p>The message identifiers of the {@link FacesMessage} to be created if
+ * the check fails.</p>
+ */
+ public static final String CSV_NOT_STRING_MESSAGE_ID = "org.apache.myfaces.commons.validator.csv.NOT_STRING";
+ public static final String CSV_INVALID_SEPARATOR_MESSAGE_ID = "org.apache.myfaces.commons.validator.csv.INVALID_SEPARATOR";
+ public static final String CSV_SUFFIX_MESSAGE_ID = "org.apache.myfaces.commons.validator.csv.SUFFIX";
+ private static final String DEFAULT_SEPARATOR = ",";
+
+ /**
+ * @JSFProperty
+ * @return the VALIDATOR_ID of the actual validator to be used
+ */
+ public abstract String getSubvalidatorId();
+
+ /**
+ * @param the VALIDATOR_ID of the actual validator to be used
+ */
+ public abstract void setSubvalidatorId(String subvalidatorId);
+
+ /**
+ * @JSFProperty
+ * literalOnly = "true"
+ * @return the separator character to separate values
+ */
+ public abstract String getSeparator();
+
+ /**
+ * @param the separator character to separate values
+ */
+ public abstract void setSeparator(String separator);
+
+ private FacesMessage addMessage(FacesMessage oldMsg, FacesMessage newMsg, int index, String suffixMessageKey) {
+ if (oldMsg != null && newMsg.getSeverity().getOrdinal() < oldMsg.getSeverity().getOrdinal())
+ return oldMsg;
+ String summaryMessageText = null;
+ String detailMessageText = null;
+ if (oldMsg == null || newMsg.getSeverity().getOrdinal() > oldMsg.getSeverity().getOrdinal()) {
+ summaryMessageText = null;
+ detailMessageText = null;
+ }
+ else {
+ summaryMessageText = oldMsg.getSummary();
+ detailMessageText = oldMsg.getDetail();
+ }
+ Object[] args = { new Integer(index + 1) };
+ FacesMessage suffixMessage = MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, suffixMessageKey, args);
+ String summarySuffix = suffixMessage.getSummary();
+ String detailSuffix = suffixMessage.getDetail();
+ if (summarySuffix == null)
+ summarySuffix = detailSuffix;
+ else if (detailSuffix == null)
+ detailSuffix = summarySuffix;
+ String summary = newMsg.getSummary();
+ if (summaryMessageText == null)
+ summaryMessageText = summary + summarySuffix;
+ else
+ summaryMessageText += ", " + summary + summarySuffix;
+ String detail = newMsg.getDetail();
+ if (detailMessageText == null)
+ detailMessageText = detail + detailSuffix;
+ else
+ detailMessageText += ", " + detail + detailSuffix;
+ return new FacesMessage(newMsg.getSeverity(), summaryMessageText, detailMessageText);
+ }
+
+ public void validate(FacesContext facesContext, UIComponent uiComponent, Object value) throws ValidatorException {
+
+ if (facesContext == null) throw new NullPointerException("facesContext");
+ if (uiComponent == null) throw new NullPointerException("uiComponent");
+
+ if (value == null)
+ {
+ return;
+ }
+
+ String suffixMessageKey = getMessage();
+ if (suffixMessageKey == null)
+ suffixMessageKey = CSV_SUFFIX_MESSAGE_ID;
+ FacesMessage facesMsg = null;
+ // value must be a String
+ if (!(value instanceof String)) {
+ Object[] args = { value };
+ throw new ValidatorException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, CSV_NOT_STRING_MESSAGE_ID, args));
+ }
+ Validator validator = facesContext.getApplication().createValidator(getSubvalidatorId());
+ if (getSeparator() == null)
+ setSeparator(DEFAULT_SEPARATOR);
+ String[] values = null;
+ try {
+ values = ((String)value).split(getSeparator());
+ }
+ catch (PatternSyntaxException e) {
+ Object[] args = { getSeparator() };
+ throw new ValidatorException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, CSV_INVALID_SEPARATOR_MESSAGE_ID, args));
+ }
+
+ // loop through the separated values and validate each one
+ for (int i = 0; i < values.length; i++) {
+ if (values[i].trim().length() == 0) {
+ continue;
+ }
+ else try {
+ validator.validate(facesContext, uiComponent, values[i]);
+ }
+ catch (ValidatorException e) {
+ facesMsg = addMessage(facesMsg, e.getFacesMessage(), i, suffixMessageKey);
+ }
+ }
+ if (facesMsg != null)
+ throw new ValidatorException(facesMsg);
+ }
+}
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCSVValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,495 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import java.util.Comparator;
+
+import javax.el.ValueExpression;
+import javax.faces.FacesException;
+import javax.faces.FactoryFinder;
+import javax.faces.application.FacesMessage;
+import javax.faces.component.EditableValueHolder;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.convert.Converter;
+import javax.faces.convert.ConverterException;
+import javax.faces.render.RenderKit;
+import javax.faces.render.RenderKitFactory;
+import javax.faces.render.Renderer;
+import javax.faces.validator.ValidatorException;
+
+import org.apache.myfaces.commons.util.MessageUtils;
+
+/**
+ *
+ * Validates this component against another component.
+ *
+ * Specify the foreign component with the for={foreign-component-id} attribute.
+ *
+ * Valid operator attribute values:
+ *
+ * equals: eq, ==, =,
+ * not equals: ne, !=,
+ * greater than: gt, >,
+ * less than: lt, <,
+ * greater than or equals: ge, >=,
+ * less than or equals: le, <=
+ *
+ * If the comparator attribute is specified, the component values are compared
+ * using the specified java.util.Comparator object.
+ * If no comparator is specified, the component values must implement Comparable
+ * and are compared using compareTo().
+ * If either value or foreign value does not implement Comparable and no Comparator
+ * is specified, validation always succeeds.
+ *
+ * Put this validator on the bottom-most component to insure that
+ * the foreign component's value has been converted and validated first.
+ *
+ * However, this validator will attempt to convert and validate the foreign
+ * component's value if this has not already occurred. This process may not
+ * be identical to the standard JSF conversion and validation process.
+ *
+ * The validation error message key is currently hardcoded as
+ *
+ * "{0} value <{1}> must be {2} {3} value <{4}>"
+ *
+ * where {0} is the parent component id,
+ * {1} is the parent component value,
+ * {2} is the operator name,
+ * {3} is the foreign component id, and
+ * {4} is the foreign component value.
+ *
+ * The alternateOperatorName attribute can specify a custom operator name.
+ * For example, use "after" instead of "greater than" when comparing dates.
+ *
+ * The message attribute can specify an alternate validation error message key.
+ * For example, use "{0} must be {2} {3}" to remove values from the message.
+ *
+ *
+ * faces-config.xml configuration:
+ *
+ * <validator>
+ * <description>CompareTo validator</description>
+ * <validator-id>org.apache.myfaces.commons.validator.CompareTo</validator-id>
+ * <validator-class>org.apache.myfaces.commons.validator.CompareToValidator</validator-class>
+ * </validator>
+ *
+ *
+ * Facelets configuration (inside a taglib.xml file):
+ *
+ * <tag>
+ * <tag-name>compareToValidator</tag-name>
+ * <validator>
+ * <validator-id>org.apache.myfaces.commons.validator.CompareTo</validator-id>
+ * </validator>
+ * </tag>
+ *
+ *
+ * Example usage:
+ *
+ * <t:inputCalendar id="startDate"/>
+ * <t:inputCalendar id="endDate">
+ * <mcv:compareToValidator operator="gt" for="startDate" />
+ * <mcv:compareToValidator operator="gt" for="startDate" message="Start date must be before end date." />
+ * <mcv:compareToValidator operator="gt" for="startDate" message="{0} must be {2} {3}" />
+ * <mcv:compareToValidator operator="gt" for="startDate" alternateOperatorName="after" />
+ * <mcv:compareToValidator operator="gt" for="startDate" message="{0} must be {2} {3}" alternateOperatorName="after" />
+ * <mcv:compareToValidator operator="gt" for="startDate" comparator="#{dateComparator}" />
+ * <t:inputCalendar>
+ *
+ *
+ * Known issues:
+ * - Operator names should be localized.
+ * - The default message key should be localized.
+ * - Perhaps an exception should be thrown if the two values are not Comparable and no Comparator is specified.
+ *
+ * @JSFValidator
+ * name = "mcv:validateCompareTo"
+ * class = "org.apache.myfaces.commons.validator.CompareToValidator"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateCompareToTag"
+ * serialuidtag = "-8879289182242196266L"
+ *
+ * @author Mike Kienenberger (latest modification by $Author$)
+ * @version $Revision$ $Date$
+ */
+public abstract class AbstractCompareToValidator extends ValidatorBase {
+ /**
+ * <p>The standard converter id for this converter.</p>
+ */
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.CompareTo";
+
+ /**
+ * <p>The message identifier of the {@link FacesMessage} to be created if
+ * the comparison check fails.</p>
+ */
+ // public static final String COMPARE_TO_MESSAGE_ID = "org.apache.myfaces.CompareTo.INVALID";
+ public static final String COMPARE_TO_MESSAGE_ID = "{0} value <{1}> must be {2} {3} value <{4}>";
+
+ public AbstractCompareToValidator(){
+ super();
+ }
+
+ public static final String OPERATOR_EQUALS = "eq";
+ public static final String OPERATOR_NOT_EQUALS = "ne";
+ public static final String OPERATOR_GREATER_THAN = "gt";
+ public static final String OPERATOR_LESS_THAN = "lt";
+ public static final String OPERATOR_GREATER_THAN_OR_EQUALS = "ge";
+ public static final String OPERATOR_LESS_THAN_OR_EQUALS = "le";
+
+ public static final String OPERATOR_EQUALS_ALT = "==";
+ public static final String OPERATOR_NOT_EQUALS_ALT = "!=";
+ public static final String OPERATOR_GREATER_THAN_ALT = ">";
+ public static final String OPERATOR_LESS_THAN_ALT = "<";
+ public static final String OPERATOR_GREATER_THAN_OR_EQUALS_ALT = ">=";
+ public static final String OPERATOR_LESS_THAN_OR_EQUALS_ALT = "<=";
+
+ public static final String OPERATOR_EQUALS_ALT2 = "=";
+
+ protected String getOperatorForString(String operatorSpecified)
+ {
+ if (OPERATOR_EQUALS.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_EQUALS;
+ else if (OPERATOR_NOT_EQUALS.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_NOT_EQUALS;
+ else if (OPERATOR_GREATER_THAN.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_GREATER_THAN;
+ else if (OPERATOR_LESS_THAN.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_LESS_THAN;
+ else if (OPERATOR_GREATER_THAN_OR_EQUALS.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_GREATER_THAN_OR_EQUALS;
+ else if (OPERATOR_LESS_THAN_OR_EQUALS.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_LESS_THAN_OR_EQUALS;
+
+ else if (OPERATOR_EQUALS_ALT.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_EQUALS;
+ else if (OPERATOR_NOT_EQUALS_ALT.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_NOT_EQUALS;
+ else if (OPERATOR_GREATER_THAN_ALT.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_GREATER_THAN;
+ else if (OPERATOR_LESS_THAN_ALT.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_LESS_THAN;
+ else if (OPERATOR_GREATER_THAN_OR_EQUALS_ALT.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_GREATER_THAN_OR_EQUALS;
+ else if (OPERATOR_LESS_THAN_OR_EQUALS_ALT.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_LESS_THAN_OR_EQUALS;
+
+ else if (OPERATOR_EQUALS_ALT2.equalsIgnoreCase(operatorSpecified))
+ return OPERATOR_EQUALS;
+
+ throw new IllegalStateException("Operator has unknown value of '" + operatorSpecified + "'");
+ }
+
+ protected String nameForOperator(String operator)
+ {
+ if (OPERATOR_EQUALS == operator)
+ return "equal to";
+ else if (OPERATOR_NOT_EQUALS == operator)
+ return "inequal to";
+ else if (OPERATOR_GREATER_THAN == operator)
+ return "greater than";
+ else if (OPERATOR_LESS_THAN == operator)
+ return "less than";
+ else if (OPERATOR_GREATER_THAN_OR_EQUALS == operator)
+ return "greater than or equal to";
+ else if (OPERATOR_LESS_THAN_OR_EQUALS == operator)
+ return "less than or equal to";
+
+ throw new IllegalStateException("Operator has unknown value of '" + operator + "'");
+ }
+
+ protected boolean validateOperatorOnComparisonResult(String operator, int result)
+ {
+ if (OPERATOR_EQUALS == operator)
+ return result == 0;
+ else if (OPERATOR_NOT_EQUALS == operator)
+ return result != 0;
+ else if (OPERATOR_GREATER_THAN == operator)
+ return result > 0;
+ else if (OPERATOR_LESS_THAN == operator)
+ return result < 0;
+ else if (OPERATOR_GREATER_THAN_OR_EQUALS == operator)
+ return result >= 0;
+ else if (OPERATOR_LESS_THAN_OR_EQUALS == operator)
+ return result <= 0;
+
+ throw new IllegalStateException("Operator has unknown value of '" + operator + "'");
+ }
+
+ public void validate(
+ FacesContext facesContext,
+ UIComponent uiComponent,
+ Object value)
+ throws ValidatorException {
+
+ if (facesContext == null) throw new NullPointerException("facesContext");
+ if (uiComponent == null) throw new NullPointerException("uiComponent");
+
+ // Don't perform validation if the value is null
+ if (value == null)
+ {
+ return;
+ }
+
+ String foreignComponentName = getFor();
+
+ UIComponent foreignComponent = (UIComponent) uiComponent.getParent().findComponent(foreignComponentName);
+ if(foreignComponent == null)
+ throw new FacesException("Unable to find component '" + foreignComponentName + "' (calling findComponent on component '" + uiComponent.getId() + "')");
+
+ if(false == foreignComponent instanceof EditableValueHolder)
+ throw new FacesException("Component '" + foreignComponent.getId() + "' does not implement EditableValueHolder");
+ EditableValueHolder foreignEditableValueHolder = (EditableValueHolder)foreignComponent;
+
+ if (foreignEditableValueHolder.isRequired() && foreignEditableValueHolder.getValue()== null ) {
+ return;
+ }
+
+ Object foreignValue;
+ if (foreignEditableValueHolder.isValid())
+ {
+ foreignValue = foreignEditableValueHolder.getValue();
+ }
+ else
+ {
+ try
+ {
+ foreignValue = getConvertedValueNonValid(facesContext, foreignComponent);
+ }
+ catch(ConverterException e)
+ {
+ /*
+ * If the value cannot be converted this should return,
+ * because does not have sense compare one
+ * foreign invalid value with other value.
+ * this force end the validation but do not continue
+ * with the next phases, because the converter
+ * of the foreign component fails and show a validation error.
+ */
+ return;
+ }
+ }
+
+ // Don't perform validation if the foreign value is null
+ if (null == foreignValue)
+ {
+ return;
+ }
+
+ String operator = getOperatorForString(getOperator());
+
+ String alternateOperatorName = getAlternateOperatorName();
+ Object[] args = {
+ uiComponent.getId(),
+ value.toString(),
+ (alternateOperatorName == null) ? nameForOperator(operator) : alternateOperatorName,
+ foreignComponent.getId(),
+ (foreignValue == null) ? foreignComponent.getId() : foreignValue.toString()
+ };
+
+ String message = getMessage();
+ if (null == message) message = COMPARE_TO_MESSAGE_ID;
+
+ Comparator comparator = createComparator();
+
+ if (null != comparator)
+ {
+ if (false == validateOperatorOnComparisonResult(operator, comparator.compare(value, foreignValue)))
+ {
+ throw new ValidatorException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, message, args));
+ }
+ }
+ else if ( (value instanceof Comparable) && (foreignValue instanceof Comparable) )
+ {
+ try
+ {
+ if (false == validateOperatorOnComparisonResult(operator, ((Comparable)value).compareTo(foreignValue)))
+ {
+ throw new ValidatorException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, message, args));
+ }
+ }
+ catch (RuntimeException exception)
+ {
+ if (exception instanceof ValidatorException)
+ {
+ throw exception;
+ }
+ else
+ {
+ throw new ValidatorException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, message + ": " + exception.getLocalizedMessage(), args));
+ }
+ }
+ }
+ else if (value instanceof Comparable)
+ {
+ throw new ClassCastException(getClassCastExceptionMessage(foreignComponent.getId(), Comparable.class, foreignValue));
+ }
+ else if (foreignValue instanceof Comparable)
+ {
+ throw new ClassCastException(getClassCastExceptionMessage(uiComponent.getId(), Comparable.class, value));
+ }
+ }
+
+ protected String getClassCastExceptionMessage(String name, Class clazz, Object object)
+ {
+ if (null == object)
+ return name + " must be type " + clazz + " but is null";
+ else return name + " must be type " + clazz + " but is type " + object.getClass();
+ }
+
+ protected Comparator createComparator()
+ {
+ Object comparator = getComparator();
+
+ if (null == comparator) return null;
+
+ if (false == comparator instanceof Comparator)
+ {
+ throw new ClassCastException(getClassCastExceptionMessage("comparator", Comparator.class, comparator));
+ }
+
+ return (Comparator)comparator;
+ }
+
+ // -------------------------------------------------------- GETTER & SETTER
+
+ /**
+ * The JSF id of the component with which to compare values.
+ *
+ * @JSFProperty
+ * @return the foreign component_id, on which a value should be validated
+ */
+ public abstract String getFor();
+
+ /**
+ * @param string the foreign component_id, on which a value should be validated
+ */
+ public abstract void setFor(String string);
+
+ /**
+ * Operator for comparison: equals: eq, ==, =, not equals: ne, !=, greater than: gt, >, less than: lt, <, greater than or equals: ge, >=, less than or equals: le, <=
+ *
+ * @JSFProperty
+ * @return
+ */
+ public abstract String getOperator();
+
+ public abstract void setOperator(String operator);
+
+ /**
+ * Value binding for an alternate java.util.Comparator object if component
+ * values don't implement Comparable
+ *
+ * @JSFProperty
+ * @return
+ */
+ public abstract Object getComparator();
+
+ public abstract void setComparator(Object comparator);
+
+ /**
+ * custom operator name in error message (ie "after" instead of "greater than" for dates)
+ *
+ * @JSFProperty
+ * @return
+ */
+ public abstract String getAlternateOperatorName();
+
+ public abstract void setAlternateOperatorName(String alternateOperatorName);
+
+ // ---------------- Borrowed to convert foreign submitted values
+
+ protected Renderer getRenderer(FacesContext context, UIComponent foreignComponent)
+ {
+ if (context == null) throw new NullPointerException("context");
+ String rendererType = foreignComponent.getRendererType();
+ if (rendererType == null) return null;
+ String renderKitId = context.getViewRoot().getRenderKitId();
+ RenderKitFactory rkf = (RenderKitFactory)FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
+ RenderKit renderKit = rkf.getRenderKit(context, renderKitId);
+ Renderer renderer = renderKit.getRenderer(foreignComponent.getFamily(), rendererType);
+ if (renderer == null)
+ {
+ getFacesContext().getExternalContext().log("No Renderer found for component " + foreignComponent + " (component-family=" + foreignComponent.getFamily() + ", renderer-type=" + rendererType + ")");
+ }
+ return renderer;
+ }
+
+ protected Converter findUIOutputConverter(FacesContext facesContext, UIComponent component)
+ {
+ Converter converter = ((EditableValueHolder)component).getConverter();
+ if (converter != null) return converter;
+
+ //Try to find out by value binding
+ ValueExpression vb = component.getValueExpression("value");
+ if (vb == null) return null;
+
+ Class valueType = vb.getType(facesContext.getELContext());
+ if (valueType == null) return null;
+
+ if (String.class.equals(valueType)) return null; //No converter needed for String type
+ if (Object.class.equals(valueType)) return null; //There is no converter for Object class
+
+ try
+ {
+ return facesContext.getApplication().createConverter(valueType);
+ }
+ catch (FacesException e)
+ {
+ getFacesContext().getExternalContext().log("No Converter for type " + valueType.getName() + " found", e);
+ return null;
+ }
+ }
+
+
+ // --------------------- borrowed and modified from UIInput ------------
+
+ protected Object getConvertedValueNonValid(FacesContext facesContext, UIComponent component)
+ throws ConverterException
+ {
+ Object componentValueObject;
+ Object submittedValue = ((EditableValueHolder) component).getSubmittedValue();
+ if (submittedValue == null)
+ {
+ componentValueObject = null;
+ }
+ else
+ {
+ Renderer renderer = getRenderer(facesContext, component);
+ if (renderer != null)
+ {
+ componentValueObject = renderer.getConvertedValue(facesContext, component, submittedValue);
+ }
+ else if (submittedValue instanceof String)
+ {
+ Converter converter = findUIOutputConverter(facesContext, component);
+ if (converter != null)
+ {
+ componentValueObject = converter.getAsObject(facesContext, component, (String)submittedValue);
+ }
+ else
+ {
+ componentValueObject = submittedValue;
+ }
+ }else{
+ componentValueObject = submittedValue;
+ }
+ }
+ return componentValueObject;
+ }
+}
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCompareToValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import org.apache.myfaces.commons.validator.ValidatorBase;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.validator.ValidatorException;
+
+/**
+ * A custom validator for creditCards, based upon Jakarta Commons.
+ *
+ * Unless otherwise specified, all attributes accept static values or EL expressions
+ *
+ * @JSFValidator
+ * name = "mcv:validateCreditCard"
+ * class = "org.apache.myfaces.commons.validator.CreditCardValidator"
+ * bodyContent = "empty"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateCreditCardTag"
+ * serialuidtag = "3810660506302799072L"
+ *
+ * @author mwessendorf (latest modification by $Author$)
+ * @version $Revision$ $Date$
+ */
+public abstract class AbstractCreditCardValidator extends ValidatorBase {
+
+ /**
+ * <p>The standard converter id for this converter.</p>
+ */
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.CreditCard";
+
+ /**
+ * <p>The message identifier of the {@link FacesMessage} to be created if
+ * the creditcard check fails.</p>
+ */
+ public static final String CREDITCARD_MESSAGE_ID = "org.apache.myfaces.commons.validator.Creditcard.INVALID";
+
+ public AbstractCreditCardValidator(){
+ }
+
+ //Field, to init the desired Validator
+ private int _initSum = 0;
+
+ private org.apache.commons.validator.CreditCardValidator creditCardValidator = null;
+
+ /**
+ *
+ */
+ public void validate(
+ FacesContext facesContext,
+ UIComponent uiComponent,
+ Object value)
+ throws ValidatorException {
+
+ if (facesContext == null) throw new NullPointerException("facesContext");
+ if (uiComponent == null) throw new NullPointerException("uiComponent");
+
+ if (value == null)
+ {
+ return;
+ }
+ initValidator();
+ if (!this.creditCardValidator.isValid(value.toString())){
+ Object[] args = {value.toString()};
+ throw new ValidatorException(getFacesMessage(CREDITCARD_MESSAGE_ID, args));
+ }
+ }
+
+
+ // -------------------------------------------------------- Private Methods
+
+ /**
+ * <p>initializes the desired validator.</p>
+ */
+
+ private void initValidator() {
+ if(isNone()){
+ //no cardtypes are allowed
+ creditCardValidator = new org.apache.commons.validator.CreditCardValidator(org.apache.commons.validator.CreditCardValidator.NONE);
+ }
+ else{
+ computeValidators();
+ creditCardValidator = new org.apache.commons.validator.CreditCardValidator(_initSum);
+ }
+ }
+
+ /**
+ * private methode, that counts the desired creditCards
+ */
+ private void computeValidators(){
+ if(isAmex()){
+ this._initSum= org.apache.commons.validator.CreditCardValidator.AMEX + _initSum;
+ }
+ if(isVisa()){
+ this._initSum= org.apache.commons.validator.CreditCardValidator.VISA+ _initSum;
+ }
+ if(isMastercard()){
+ this._initSum= org.apache.commons.validator.CreditCardValidator.MASTERCARD+ _initSum;
+ }
+ if(isDiscover()){
+ this._initSum= org.apache.commons.validator.CreditCardValidator.DISCOVER+ _initSum;
+ }
+ }
+
+ //GETTER & SETTER
+
+ /**
+ * american express cards
+ *
+ * @JSFProperty
+ * defaultValue = "true"
+ */
+ public abstract boolean isAmex();
+
+ /**
+ * validation for discover
+ *
+ * @JSFProperty
+ * defaultValue = "true"
+ */
+ public abstract boolean isDiscover();
+
+ /**
+ * validation for mastercard
+ *
+ * @JSFProperty
+ * defaultValue = "true"
+ */
+ public abstract boolean isMastercard();
+
+ /**
+ * none of the given cardtypes is allowed.
+ *
+ * @JSFProperty
+ * defaultValue = "false"
+ */
+ public abstract boolean isNone();
+
+ /**
+ * validation for visa
+ *
+ * @JSFProperty
+ * defaultValue = "true"
+ */
+ public abstract boolean isVisa();
+
+ public abstract void setAmex(boolean b);
+
+ public abstract void setDiscover(boolean b);
+
+ public abstract void setMastercard(boolean b);
+
+ public abstract void setNone(boolean b);
+
+ public abstract void setVisa(boolean b);
+
+}
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractCreditCardValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.StateHolder;
+import javax.faces.component.UIComponent;
+import javax.faces.component.ValueHolder;
+import javax.faces.context.FacesContext;
+import javax.faces.convert.Converter;
+import javax.faces.convert.DateTimeConverter;
+import javax.faces.validator.Validator;
+import javax.faces.validator.ValidatorException;
+
+import org.apache.myfaces.commons.validator.model.DateListProvider;
+
+/**
+ * Validate that the date entered is within a given restriction.
+ *
+ * @JSFValidator
+ * name = "mcv:validateDateRestriction"
+ * class = "org.apache.myfaces.commons.validator.DateRestrictionValidator"
+ * bodyContent = "empty"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateDateRestrictionTag"
+ *
+ */
+public abstract class AbstractDateRestrictionValidator extends ValidatorBase
+ implements Validator, StateHolder
+{
+
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.DateRestriction";
+
+ /**
+ * <p>The message identifier of the {@link javax.faces.application.FacesMessage}
+ * to be created if the valid days value check fails. The message format
+ * string for this message may optionally include <code>{0}</code>,
+ * <code>{1}</code> and <code>{3}</code> placeholders,
+ * which will be replaced by user input, component label and configured
+ * days value.</p>
+ */
+ public static final String DAY_MESSAGE_ID = "org.apache.myfaces.commons.validator.DateRestrictionValidator.DAY";
+
+ /**
+ * <p>The message identifier of the {@link javax.faces.application.FacesMessage}
+ * to be created if the valid month value check fails. The message format
+ * string for this message may optionally include <code>{0}</code>,
+ * <code>{1}</code> and <code>{3}</code> placeholders,
+ * which will be replaced by user input, component label and configured
+ * month value.</p>
+ */
+ public static final String MONTH_MESSAGE_ID = "org.apache.myfaces.commons.validator.DateRestrictionValidator.MONTH";
+
+ /**
+ * <p>The message identifier of the {@link javax.faces.application.FacesMessage}
+ * to be created if the valid weekdays value check fails. The message format
+ * string for this message may optionally include <code>{0}</code>,
+ * <code>{1}</code> and <code>{3}</code> placeholders,
+ * which will be replaced by user input, component label and configured
+ * weekdays value.</p>
+ */
+ public static final String WEEKDAY_MESSAGE_ID = "org.apache.myfaces.commons.validator.DateRestrictionValidator.WEEKDAY";
+
+ /**
+ * Construct a {@link Validator} with no preconfigured limits.
+ */
+ public AbstractDateRestrictionValidator()
+ {
+ super();
+ _initMaps();
+ }
+
+ /**
+ * @JSFProperty
+ */
+ public abstract String[] getInvalidMonths();
+
+ public abstract void setInvalidMonths(String[] invalidMonths);
+
+ /**
+ * @JSFProperty
+ */
+ public abstract String[] getInvalidDaysOfWeek();
+
+ public abstract void setInvalidDaysOfWeek(String[] invalidDaysOfWeek);
+
+ /**
+ * @JSFProperty
+ */
+ public abstract DateListProvider getInvalidDays();
+
+ public abstract void setInvalidDays(DateListProvider invalidDays);
+
+ /**
+ * @exception IllegalArgumentException if <code>value</code> is not of type
+ * {@link java.util.Date}
+ */
+ public void validate(FacesContext context, UIComponent component,
+ Object value) throws ValidatorException
+ {
+ if ((context == null) || (component == null))
+ {
+ throw new NullPointerException(("NULL_FACESCONTEXT_OR_UICOMPONENT"));
+ }
+
+ if (value != null)
+ {
+ Calendar calendar = getCalendar();
+ calendar.setTime(getDateValue(value));
+ Date convertedDate = calendar.getTime();
+
+ String weekday = _dayMap.get(calendar.get(Calendar.DAY_OF_WEEK));
+ if (_getInvalidDaysOfWeek().contains(weekday))
+ {
+ throw new ValidatorException(getWrongWeekDayMessage(context,
+ component, value, weekday));
+ }
+
+ String month = _monthMap.get(calendar.get(Calendar.MONTH));
+ if (_getInvalidMonths().contains(month))
+ {
+ throw new ValidatorException(getWrongMonthMessage(context,
+ component, value, month));
+ }
+
+ DateListProvider dlp = getInvalidDays();
+ List<Date> dates = null;
+ if (dlp != null)
+ {
+ dates = dlp.getDateList(context, calendar, calendar.getTime(),
+ calendar.getTime());
+ }
+
+ if (dates != null)
+ {
+ for (Date date : dates)
+ {
+ //range is only one submitted day...
+ if (!date.before(convertedDate)
+ && !date.after(convertedDate))
+ {
+ throw new ValidatorException(getWrongDayMessage(
+ context, component, value, date));
+ }
+ }
+ }
+ }
+ }
+
+ private Converter getConverter(FacesContext context, UIComponent component)
+ {
+ Converter converter = null;
+ if (component instanceof ValueHolder)
+ {
+ converter = ((ValueHolder) component).getConverter();
+ }
+
+ if (converter == null)
+ {
+ // Use the DateTimeConverter's CONVERTER_ID, not Date.class,
+ // because there is in fact not usually a converter registered
+ // at Date.class
+ converter = context.getApplication().createConverter(
+ DateTimeConverter.CONVERTER_ID);
+ }
+
+ assert (converter != null);
+
+ return converter;
+ }
+
+ protected Calendar getCalendar()
+ {
+ //TODO: make it better
+ return Calendar.getInstance();
+
+ }
+
+ /**
+ * Parses the already converted value to a <code>java.util.Date</code>.
+ * @param value converted value
+ * @return fulltyped <code>java.util.Date</code>
+ * @throws IllegalArgumentException
+ */
+ protected static Date getDateValue(Object value)
+ throws IllegalArgumentException
+ {
+ if (value instanceof Date)
+ {
+ return ((Date) value);
+ }
+
+ throw new IllegalArgumentException("value is not a date type");
+ }
+
+ private FacesMessage getWrongWeekDayMessage(FacesContext context,
+ UIComponent component, Object value, Object weekday)
+ {
+ Converter converter = getConverter(context, component);
+ Object cWeekday = _getConvertedValue(context, component, converter,
+ weekday);
+ Object[] params = { cWeekday };
+ return getFacesMessage(WEEKDAY_MESSAGE_ID, params);
+ }
+
+ private FacesMessage getWrongMonthMessage(FacesContext context,
+ UIComponent component, Object value, Object month)
+ {
+ Converter converter = getConverter(context, component);
+ Object cMonth = _getConvertedValue(context, component, converter, month);
+ Object[] params = { cMonth };
+ return getFacesMessage(MONTH_MESSAGE_ID, params);
+ }
+
+ private FacesMessage getWrongDayMessage(FacesContext context,
+ UIComponent component, Object value, Object day)
+ {
+ Converter converter = getConverter(context, component);
+
+ Object cValue = _getConvertedValue(context, component, converter, value);
+ Object cDay = _getConvertedValue(context, component, converter, day);
+
+ Object[] params = { cValue, cDay };
+
+ return getFacesMessage(DAY_MESSAGE_ID, params);
+ }
+
+ private Object _getConvertedValue(FacesContext context,
+ UIComponent component, Converter converter, Object value)
+ {
+ return converter.getAsString(context, component, value);
+ }
+
+ private final Set<String> _getInvalidMonths()
+ {
+ Set<String> monthSet = new HashSet<String>();
+ String[] month = getInvalidMonths();
+ if (month != null)
+ {
+
+ for (int i = 0; i < month.length; i++)
+ {
+ monthSet.add(month[i].toLowerCase());
+ }
+ }
+
+ return monthSet;
+ }
+
+ private final Set<String> _getInvalidDaysOfWeek()
+ {
+ Set<String> daysOfWeekSet = new HashSet<String>();
+ String[] daysOfWeek = getInvalidDaysOfWeek();
+ if (daysOfWeek != null)
+ {
+
+ for (int i = 0; i < daysOfWeek.length; i++)
+ {
+ daysOfWeekSet.add(daysOfWeek[i].toLowerCase());
+ }
+ }
+
+ return daysOfWeekSet;
+ }
+
+ private void _initMaps()
+ {
+ _dayMap = new HashMap<Integer, String>();
+ _dayMap.put(Calendar.SUNDAY, "sun");
+ _dayMap.put(Calendar.MONDAY, "mon");
+ _dayMap.put(Calendar.TUESDAY, "tue");
+ _dayMap.put(Calendar.WEDNESDAY, "wed");
+ _dayMap.put(Calendar.THURSDAY, "thu");
+ _dayMap.put(Calendar.FRIDAY, "fri");
+ _dayMap.put(Calendar.SATURDAY, "sat");
+
+ _monthMap = new HashMap<Integer, String>();
+ _monthMap.put(Calendar.JANUARY, "jan");
+ _monthMap.put(Calendar.FEBRUARY, "feb");
+ _monthMap.put(Calendar.MARCH, "mar");
+ _monthMap.put(Calendar.APRIL, "apr");
+ _monthMap.put(Calendar.MAY, "may");
+ _monthMap.put(Calendar.JUNE, "jun");
+ _monthMap.put(Calendar.JULY, "jul");
+ _monthMap.put(Calendar.AUGUST, "aug");
+ _monthMap.put(Calendar.SEPTEMBER, "sep");
+ _monthMap.put(Calendar.OCTOBER, "oct");
+ _monthMap.put(Calendar.NOVEMBER, "nov");
+ _monthMap.put(Calendar.DECEMBER, "dec");
+ }
+
+ private Map<Integer, String> _dayMap = null;
+ private Map<Integer, String> _monthMap = null;
+}
\ No newline at end of file
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractDateRestrictionValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.validator.ValidatorException;
+
+import org.apache.commons.validator.GenericValidator;
+import org.apache.myfaces.commons.validator.ValidatorBase;
+
+/**
+ * A custom validator for reg. expr., based upons Jakarta Commons.
+ *
+ * Unless otherwise specified, all attributes accept static values or EL expressions.
+ *
+ * @JSFValidator
+ * name = "mcv:validateRegExpr"
+ * class = "org.apache.myfaces.commons.validator.RegExprValidator"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateRegExprTag"
+ * serialuidtag = "-449945949876262076L"
+ *
+ * @author mwessendorf (latest modification by $Author$)
+ * @version $Revision$ $Date$
+ */
+
+public abstract class AbstractRegExprValidator extends ValidatorBase {
+ /**
+ * <p>The standard converter id for this converter.</p>
+ */
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.RegExpr";
+
+ /**
+ * <p>The message identifier of the {@link FacesMessage} to be created if
+ * the regex check fails.</p>
+ */
+ public static final String REGEXPR_MESSAGE_ID = "org.apache.myfaces.commons.validator.RegExpr.INVALID";
+
+ public AbstractRegExprValidator(){
+ }
+
+ public void validate(
+ FacesContext facesContext,
+ UIComponent uiComponent,
+ Object value)
+ throws ValidatorException {
+
+ if (facesContext == null) throw new NullPointerException("facesContext");
+ if (uiComponent == null) throw new NullPointerException("uiComponent");
+
+ if (value == null)
+ {
+ return;
+ }
+ Object[] args = {value.toString()};
+ if(!GenericValidator.matchRegexp(value.toString(),"^"+getPattern()+"$")){
+ throw new ValidatorException(getFacesMessage(REGEXPR_MESSAGE_ID, args));
+ }
+ }
+
+ // -------------------------------------------------------- GETTER & SETTER
+
+ /**
+ * the pattern, which is the base of the validation
+ *
+ * @JSFProperty
+ * literalOnly = "true"
+ * @return the pattern, on which a value should be validated
+ */
+ public abstract String getPattern();
+
+ /**
+ * @param string the pattern, on which a value should be validated
+ */
+ public abstract void setPattern(String string);
+
+}
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractRegExprValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.validator.ValidatorException;
+
+/**
+ * A custom validator for url format, based upons Jakarta Commons.
+ *
+ * @JSFValidator
+ * name = "mcv:validateUrl"
+ * class = "org.apache.myfaces.commons.validator.UrlValidator"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateUrlTag"
+ * serialuidtag = "6041422002721046221L"
+ *
+ * @author Fabian Frederick
+ *
+ * @version $Revision$ $Date$
+ */
+public abstract class AbstractUrlValidator extends ValidatorBase {
+
+ /**
+ * <p>The standard converter id for this converter.</p>
+ */
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.Url";
+ /**
+ * <p>The message identifier of the {@link FacesMessage} to be created if
+ * the maximum length check fails.</p>
+ */
+ public static final String URL_MESSAGE_ID = "org.apache.myfaces.commons.validator.Url.INVALID";
+
+ public AbstractUrlValidator(){
+
+ }
+
+ /**
+ * method that validates an url address.
+ * it uses the commons-validator
+ */
+ public void validate(
+ FacesContext facesContext,
+ UIComponent uiComponent,
+ Object value)
+ throws ValidatorException {
+
+
+ if (facesContext == null) throw new NullPointerException("facesContext");
+ if (uiComponent == null) throw new NullPointerException("uiComponent");
+
+ if (value == null)
+ {
+ return;
+ }
+
+ org.apache.commons.validator.UrlValidator urlValidator = initValidator();
+
+ if (!urlValidator.isValid(value.toString())) {
+ Object[] args = {value.toString()};
+ throw new ValidatorException(getFacesMessage(URL_MESSAGE_ID, args));
+ }
+
+ }
+
+ private org.apache.commons.validator.UrlValidator initValidator()
+ {
+ int options = 0;
+
+ if (isAllow2Slashes())
+ {
+ options = options | org.apache.commons.validator.UrlValidator.ALLOW_2_SLASHES;
+ }
+
+ if (isAllowAllSchemas())
+ {
+ options = options | org.apache.commons.validator.UrlValidator.ALLOW_ALL_SCHEMES;
+ }
+
+ String [] schemesList = getSchemesList();
+ org.apache.commons.validator.UrlValidator urlValidator = null;
+ if (schemesList == null){
+ urlValidator = new
+ org.apache.commons.validator.UrlValidator(options);
+ }
+ else
+ {
+ urlValidator = new
+ org.apache.commons.validator.UrlValidator(schemesList,options);
+ }
+ return urlValidator;
+ }
+
+ private String[] getSchemesList(){
+ if (getSchemes() == null)
+ {
+ return null;
+ }
+ String [] list = getSchemes().split(",");
+ String [] resp = new String [list.length];
+
+ for (int i = 0; i < list.length; i++)
+ {
+ resp[i] = list[i].trim();
+ }
+ return resp;
+ }
+
+ public abstract void setSchemes(String _schemes);
+
+ /**
+ * CSV values that indicates the set of schemes to check this url.
+ *
+ * If allowAllSchemas = true, the values of this field are ignored.
+ *
+ * If no schemes are provided, default to this set ("http", "https", "ftp").
+ *
+ * @JSFProperty
+ */
+ public abstract String getSchemes();
+
+ public abstract void setAllow2Slashes(boolean _allow2Slashes);
+
+ /**
+ * Allow two slashes in the path component of the URL.
+ *
+ * @JSFProperty
+ * defaultValue = "false"
+ */
+ public abstract boolean isAllow2Slashes();
+
+ public abstract void setAllowAllSchemas(boolean _allowAllSchemas);
+
+ /**
+ * Allows all validly formatted schemes to pass validation instead of
+ * supplying a set of valid schemes.
+ *
+ * @JSFProperty
+ * defaultValue = "false"
+ */
+ public abstract boolean isAllowAllSchemas();
+
+}
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/AbstractUrlValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.validator.ValidatorException;
+
+import org.apache.myfaces.commons.util.MessageUtils;
+
+/**
+ * A custom validator for isbn codes, based upons Jakarta Commons.
+ *
+ * @JSFValidator
+ * name = "mcv:validateISBN"
+ * tagClass = "org.apache.myfaces.commons.validator.ValidateISBNTag"
+ * serialuidtag = "5230653358032218656L"
+ *
+ * @author <a href="mailto:matzew@apache.org">Matthias Weßendorf</a> (latest modification by $Author$)
+ * @version $Revision$ $Date$
+ */
+
+public class ISBNValidator extends ValidatorBase {
+
+ /**
+ * <p>The standard converter id for this converter.</p>
+ */
+ public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.ISBN";
+ /**
+ * <p>The message identifier of the {@link FacesMessage} to be created if
+ * the maximum length check fails.</p>
+ */
+ public static final String ISBN_MESSAGE_ID = "org.apache.myfaces.commons.validator.ISBN.INVALID";
+
+ /**
+ * <p>isbnValidator</p>
+ */
+ private org.apache.commons.validator.ISBNValidator isbnValidator;
+
+ public ISBNValidator(){
+ isbnValidator = new org.apache.commons.validator.ISBNValidator();
+ }
+
+ /**
+ * methode that validates isbn codes.
+ * it uses the commons-validator
+ */
+ public void validate(
+ FacesContext facesContext,
+ UIComponent uiComponent,
+ Object value)
+ throws ValidatorException {
+
+
+ if (facesContext == null) throw new NullPointerException("facesContext");
+ if (uiComponent == null) throw new NullPointerException("uiComponent");
+
+ if (value == null)
+ {
+ return;
+ }
+
+ if (!isbnValidator.isValid( value.toString())) {
+ Object[] args = {value.toString()};
+ String message = getMessage();
+ if (null == message) message = ISBN_MESSAGE_ID;
+
+ throw new ValidatorException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, message, args));
+ }
+
+
+ }
+
+}
\ No newline at end of file
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ISBNValidator.java
------------------------------------------------------------------------------
svn:keywords = Date Author Id Revision HeadURL
Added: myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ValidatorBaseTag.java
URL: http://svn.apache.org/viewvc/myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ValidatorBaseTag.java?rev=669047&view=auto
==============================================================================
--- myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ValidatorBaseTag.java (added)
+++ myfaces/commons/trunk/myfaces-commons-validators/src/main/java/org/apache/myfaces/commons/validator/ValidatorBaseTag.java Tue Jun 17 18:39:59 2008
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.myfaces.commons.validator;
+
+import javax.el.ValueExpression;
+import javax.faces.context.FacesContext;
+import javax.faces.validator.Validator;
+import javax.faces.webapp.ValidatorELTag;
+import javax.servlet.jsp.JspException;
+
+/**
+ * ValidatorBaseTag provides support for ValidatorBase subclasses.
+ * ValidatorBaseTag subclass tld entries should include the following to pick up attribute defintions.
+ * &ext_validator_base_attributes;
+ *
+ * @author mkienenb (latest modification by $Author$)
+ * @version $Revision$
+ */
+public abstract class ValidatorBaseTag extends ValidatorELTag {
+ private static final long serialVersionUID = 4416508071412794682L;
+ private ValueExpression _message = null;
+ private ValueExpression _detailMessage = null;
+ private ValueExpression _summaryMessage = null;
+
+ public void setMessage(ValueExpression string) {
+ _message = string;
+ }
+
+ public void setDetailMessage(ValueExpression detailMessage)
+ {
+ _detailMessage = detailMessage;
+ }
+
+ public void setSummaryMessage(ValueExpression summaryMessage)
+ {
+ _summaryMessage = summaryMessage;
+ }
+
+ protected void _setProperties(Validator v) throws JspException {
+
+ ValidatorBase validator = (ValidatorBase) v;
+
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+
+ if(_message != null && _detailMessage != null)
+ throw new JspException("you may not set detailMessage and detailMessage together - they serve the same purpose.");
+
+ ValueExpression detailMessage = _message;
+
+ if(_detailMessage != null)
+ detailMessage = _detailMessage;
+
+ if (detailMessage != null)
+ {
+ if (!_detailMessage.isLiteralText())
+ {
+ validator.setValueExpression("detailMessage",_detailMessage);
+ }
+ else
+ {
+ validator.setDetailMessage((String)_detailMessage.getValue(facesContext.getELContext()));
+ }
+ }
+
+ if (_summaryMessage != null)
+ {
+ if (!_summaryMessage.isLiteralText())
+ {
+ validator.setValueExpression("summaryMessage",_summaryMessage);
+ }
+ else
+ {
+ validator.setSummaryMessage((String)_summaryMessage.getValue(facesContext.getELContext()));
+ }
+ }
+ }
+
+ public void release()
+ {
+ super.release();
+ _message= null;
+ _detailMessage = null;
+ _summaryMessage = null;
+ }
+}