001 // Copyright 2006, 2008, 2009 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package org.apache.tapestry5.internal.bindings; 016 017 import org.apache.tapestry5.Binding; 018 import org.apache.tapestry5.ComponentResources; 019 import org.apache.tapestry5.Field; 020 import org.apache.tapestry5.FieldValidator; 021 import org.apache.tapestry5.internal.services.StringInterner; 022 import org.apache.tapestry5.ioc.Location; 023 import org.apache.tapestry5.ioc.internal.util.TapestryException; 024 import org.apache.tapestry5.services.BindingFactory; 025 import org.apache.tapestry5.services.FieldValidatorSource; 026 027 /** 028 * Factory for bindings that provide a {@link org.apache.tapestry5.FieldValidator} based on a validator specification. 029 * This binding factory is only useable with components that implement the {@link org.apache.tapestry5.Field} 030 * interface. 031 */ 032 public class ValidateBindingFactory implements BindingFactory 033 { 034 private final FieldValidatorSource fieldValidatorSource; 035 036 private final StringInterner interner; 037 038 public ValidateBindingFactory(FieldValidatorSource fieldValidatorSource, StringInterner interner) 039 { 040 this.fieldValidatorSource = fieldValidatorSource; 041 this.interner = interner; 042 } 043 044 public Binding newBinding(String description, ComponentResources container, 045 ComponentResources component, final String expression, Location location) 046 { 047 Object fieldAsObject = component.getComponent(); 048 049 if (!Field.class.isInstance(fieldAsObject)) 050 throw new TapestryException(BindingsMessages.validateBindingForFieldsOnly(component), 051 location, null); 052 053 final Field field = (Field) fieldAsObject; 054 055 return new InvariantBinding(location, FieldValidator.class, interner.intern(description + ": " + expression)) 056 { 057 public Object get() 058 { 059 // The expression is a validator specification, such as "required,minLength=5". 060 // ValidatorBindingFactory is the odd man out becasuse it needs the binding component (the 061 // component whose parameter is to be bound) rather than the containing component, the way 062 // most factories work. 063 064 return fieldValidatorSource.createValidators(field, expression); 065 } 066 }; 067 } 068 }