1 16 package org.apache.cocoon.forms.validation.impl; 17 18 import java.util.Map ; 19 20 import org.apache.avalon.framework.CascadingRuntimeException; 21 import org.apache.avalon.framework.context.Context; 22 import org.apache.cocoon.components.ContextHelper; 23 import org.apache.cocoon.forms.formmodel.Widget; 24 import org.apache.cocoon.forms.util.JavaScriptHelper; 25 import org.apache.cocoon.forms.validation.ValidationError; 26 import org.apache.cocoon.forms.validation.ValidationErrorAware; 27 import org.apache.cocoon.forms.validation.WidgetValidator; 28 import org.apache.excalibur.xml.sax.XMLizable; 29 import org.mozilla.javascript.Function; 30 31 54 public class JavaScriptValidator implements WidgetValidator { 55 56 private final Function function; 57 private final Context avalonContext; 58 59 public JavaScriptValidator(Context context, Function function) { 60 this.function = function; 61 this.avalonContext = context; 62 } 63 64 public final boolean validate(Widget widget) { 65 66 Map objectModel = ContextHelper.getObjectModel(this.avalonContext); 67 68 Object result; 69 70 try { 71 result = JavaScriptHelper.callFunction(this.function, widget, new Object [] {widget}, objectModel); 72 } catch(RuntimeException re) { 73 throw re; } catch(Exception e) { 75 throw new CascadingRuntimeException("Error invoking JavaScript event handler", e); 76 } 77 78 if (result == null) { 79 throw new RuntimeException ("Validation script did not return a value"); 80 } 81 82 if (result instanceof Boolean ) { 83 return ((Boolean )result).booleanValue(); 84 } 85 86 if (result instanceof ValidationError) { 87 ((ValidationErrorAware)widget).setValidationError((ValidationError)result); 89 return false; 90 } 91 92 if (result instanceof String ) { 93 ((ValidationErrorAware)widget).setValidationError(new ValidationError((String )result, false)); 95 return false; 96 } 97 98 if (result instanceof XMLizable) { 99 ((ValidationErrorAware)widget).setValidationError(new ValidationError((XMLizable)result)); 101 return false; 102 } 103 104 throw new RuntimeException ("Validation script returned an unexpected value of type " + result.getClass()); 105 } 106 } 107 | Popular Tags |