001 /*
002 * Copyright 2004 Chris Nelson
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
007 * Unless required by applicable law or agreed to in writing,
008 * software distributed under the License is distributed on an "AS IS" BASIS,
009 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010 * See the License for the specific language governing permissions and limitations under the License.
011 */
012 package org.trails.component;
013
014 import java.util.List;
015
016 import ognl.Ognl;
017 import org.apache.commons.lang.StringUtils;
018 import org.trails.exception.TrailsRuntimeException;
019
020
021 public class IdentifierSelectionModel extends AbstractPropertySelectionModel
022 {
023 private String idProperty = "id";
024
025 public IdentifierSelectionModel(List instances, String idProperty)
026 {
027 super(instances);
028 this.idProperty = idProperty;
029 }
030
031 public IdentifierSelectionModel(List instances, String idProperty, boolean allowNone)
032 {
033 super(instances, allowNone);
034 this.idProperty = idProperty;
035 }
036
037 /* (non-Javadoc)
038 * @see org.apache.tapestry.form.IPropertySelectionModel#getValue(int)
039 */
040 public String getValue(int index)
041 {
042 try
043 {
044 if (allowNone && index == 0)
045 {
046 return DEFAULT_NONE_VALUE;
047 } else
048 {
049 return Ognl.getValue(idProperty,instances.get(index)).toString();
050 }
051 } catch (Exception e)
052 {
053 throw new TrailsRuntimeException(e);
054 }
055 }
056
057 /* (non-Javadoc)
058 * @see org.apache.tapestry.form.IPropertySelectionModel#translateValue(java.lang.String)
059 */
060 public Object translateValue(String value)
061 {
062 if (StringUtils.isEmpty(value)) return null;
063 List realInstances = allowNone ? instances.subList(1, instances.size()) : instances;
064 try
065 {
066 if (allowNone)
067 {
068 if (value.equals(DEFAULT_NONE_VALUE)) return null;
069 }
070 List matches = (List) Ognl.getValue(
071 "#root.{? #this." + idProperty + ".toString() == \"" + value + "\" }",
072 realInstances);
073 if (matches.size() > 0) return matches.get(0);
074 return null;
075 } catch (Exception e)
076 {
077 throw new TrailsRuntimeException(e);
078 }
079 }
080
081
082 public boolean isDisabled(int i)
083 {
084 return false;
085 }
086 }