001// Copyright 2004, 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 015package org.apache.tapestry.coerce; 016 017import java.util.Iterator; 018import java.util.List; 019 020import org.apache.hivemind.lib.util.StrategyRegistry; 021import org.apache.hivemind.lib.util.StrategyRegistryImpl; 022 023/** 024 * A service implementation that works around an 025 * {@link org.apache.hivemind.lib.util.StrategyRegistry}. The registry is contructed from a 026 * configuration that follows the <code>tapestry.coerce.Converters</code> schema (a List of 027 * {@link org.apache.tapestry.coerce.TypeConverterContribution}plus an additional converter for 028 * nulls. 029 * 030 * @author Howard M. Lewis Ship 031 * @since 4.0 032 */ 033public final class TypeConverterWrapper implements TypeConverter 034{ 035 private StrategyRegistry _registry = new StrategyRegistryImpl(); 036 037 private List _contributions; 038 039 private TypeConverter _nullConverter; 040 041 public void initializeService() 042 { 043 Iterator i = _contributions.iterator(); 044 045 while (i.hasNext()) 046 { 047 TypeConverterContribution c = (TypeConverterContribution) i.next(); 048 049 _registry.register(c.getSubjectClass(), c.getConverter()); 050 } 051 } 052 053 public Object convertValue(Object value) 054 { 055 if (value == null) 056 { 057 if (_nullConverter == null) 058 return null; 059 060 return _nullConverter.convertValue(null); 061 } 062 063 TypeConverter delegate = (TypeConverter) _registry.getStrategy(value.getClass()); 064 065 return delegate.convertValue(value); 066 } 067 068 /** 069 * Sets the List of {@link org.apache.tapestry.coerce.TypeConverterContribution}s. 070 */ 071 072 public void setContributions(List contributions) 073 { 074 _contributions = contributions; 075 } 076 077 /** 078 * Sets the converter used to convert null. 079 */ 080 081 public void setNullConverter(TypeConverter nullConverter) 082 { 083 _nullConverter = nullConverter; 084 } 085}