001    /*
002     * Apache License
003     * Version 2.0, January 2004
004     * http://www.apache.org/licenses/
005     *
006     * Copyright 1996-2008 by Sven Homburg
007     *
008     * Licensed under the Apache License, Version 2.0 (the "License");
009     * you may not use this file except in compliance with the License.
010     * You may obtain a copy of the License at
011     *
012     * http://www.apache.org/licenses/LICENSE-2.0
013     */
014    
015    package org.chenillekit.tapestry.core.encoders;
016    
017    import java.util.List;
018    
019    import org.apache.tapestry5.ValueEncoder;
020    import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
021    import org.apache.tapestry5.ioc.services.PropertyAccess;
022    
023    /**
024     * @version $Id: GenericValueEncoder.java 670 2010-07-19 09:22:02Z mlusetti $
025     */
026    public class GenericValueEncoder<T> implements ValueEncoder<T>
027    {
028        private List<T> _objectList;
029        private final PropertyAccess _access;
030        private String _valueFieldName = null;
031    
032        public GenericValueEncoder(List<T> objectList)
033        {
034            this(objectList, null, null);
035        }
036    
037        public GenericValueEncoder(List<T> objectList, String valueFieldName, PropertyAccess propertyAccess)
038        {
039            assert objectList != null;
040    
041            // more carfully i think, so we copy the object list
042            _objectList = CollectionFactory.newList(objectList);
043            _valueFieldName = valueFieldName;
044            _access = propertyAccess;
045        }
046    
047        public String toClient(T serverValue)
048        {
049            return getServerValueAsString(serverValue);
050        }
051    
052        public T toValue(String clientValue)
053        {
054            T serverValue = null;
055    
056            for (T obj : _objectList)
057            {
058                String value = getServerValueAsString(obj);
059                if (value.equals(clientValue))
060                {
061                    serverValue = obj;
062                    break;
063                }
064            }
065    
066            return serverValue;
067        }
068    
069        private String getServerValueAsString(T serverValue)
070        {
071            String clientValue = "";
072    
073            if (_valueFieldName != null && _access != null)
074                clientValue = String.valueOf(_access.get(serverValue, _valueFieldName));
075            else
076                clientValue = String.valueOf(serverValue);
077    
078            return clientValue;
079        }
080    }