You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@cocoon.apache.org by Scott Yeadon <sc...@anu.edu.au> on 2004/08/05 06:21:25 UTC

CForms: providing validation via java classes

Hello,

If anyone wants to do validation via Java classes here is one possible 
way (where no actual Cocoon code needs to be changed):

Create a JavaClassValidatorBuilder which operates the same way as the 
ListenerBuilder:

package my.package;

import java.lang.Exception;
import org.apache.cocoon.forms.formmodel.WidgetDefinition;
import org.apache.cocoon.forms.validation.WidgetValidatorBuilder;
import org.apache.cocoon.forms.validation.WidgetValidator;
import org.apache.cocoon.forms.util.DomHelper;
import org.apache.cocoon.util.ClassUtils;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.w3c.dom.Element;

public class JavaClassValidatorBuilder implements 
WidgetValidatorBuilder, ThreadSafe
{
    public WidgetValidator build(Element element,
                                  WidgetDefinition widget) throws Exception
    {
        String name = DomHelper.getAttribute(element, "class");

        Object validator = ClassUtils.newInstance(name);
        if (Class.forName(WIDGET_VALIDATOR_PACKAGE + PACKAGE_SEPARATOR + 
WIDGET + WIDGET_VALIDATOR_CLASSNAME).isAssignableFrom(validator.getClass()))
        {
            return (WidgetValidator)validator;
        }
        else
        {
            throw new Exception("Class " + validator.getClass() + " is 
not a " + WIDGET_VALIDATOR_CLASSNAME);
        }
    }
}

Where:
WIDGET_VALIDATOR_PACKAGE is "org.apache.cocoon.forms.validation"
PACKAGE_SEPARATOR is "."
WIDGET_VALIDATOR_CLASSNAME is "WidgetValidator"

Update the coccon.xconf file's forms-validators element with:
<validator class="my.package.JavaClassValidatorBuilder" name="java"/>

Restart cocoon and works fine, can now add tagging such as
<fd:validation>
    <java class="my.other.package.MyJavaClassThatValidatesStuff"/>
</fd:validation>

Scott.

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@cocoon.apache.org
For additional commands, e-mail: users-help@cocoon.apache.org