001    // Copyright 2005 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.tapestry.bean;
016    
017    import org.apache.hivemind.util.Defense;
018    import org.apache.hivemind.util.PropertyUtils;
019    import org.apache.tapestry.IBeanProvider;
020    import org.apache.tapestry.IBinding;
021    import org.apache.tapestry.IComponent;
022    import org.apache.tapestry.binding.BindingConstants;
023    import org.apache.tapestry.binding.BindingSource;
024    
025    /**
026     * An {@link org.apache.tapestry.bean.IBeanInitializer} implementation that uses an
027     * {@link org.apache.tapestry.IBinding} to obtain the value which will be assigned to the bean
028     * property.
029     * 
030     * @author Howard M. Lewis Ship
031     * @since 4.0
032     */
033    public class BindingBeanInitializer extends AbstractBeanInitializer
034    {
035        private BindingSource _bindingSource;
036    
037        private String _bindingReference;
038    
039        /** @since 4.0 */
040        public BindingBeanInitializer(BindingSource source)
041        {
042            Defense.notNull(source, "source");
043    
044            _bindingSource = source;
045        }
046    
047        /**
048         * @since 4.0
049         */
050        public void setBindingReference(String bindingReference)
051        {
052            _bindingReference = bindingReference;
053        }
054    
055        /** @since 4.0 */
056        public String getBindingReference()
057        {
058            return _bindingReference;
059        }
060    
061        public void setBeanProperty(IBeanProvider provider, Object bean)
062        {
063            IComponent component = provider.getComponent();
064    
065            String description = BeanMessages.propertyInitializerName(_propertyName);
066    
067            IBinding binding = _bindingSource.createBinding(
068                    component,
069                    description,
070                    _bindingReference,
071                    BindingConstants.OGNL_PREFIX,
072                    getLocation());
073    
074            Class propertyType = PropertyUtils.getPropertyType(bean, _propertyName);
075    
076            Object bindingValue = binding.getObject(propertyType);
077    
078            setBeanProperty(bean, bindingValue);
079        }
080    }