001// Copyright 2010-2013 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.
014package org.apache.tapestry5.internal.services;
015
016import org.apache.tapestry5.OptionModel;
017import org.apache.tapestry5.SelectModel;
018import org.apache.tapestry5.commons.services.PropertyAccess;
019import org.apache.tapestry5.commons.util.CollectionFactory;
020import org.apache.tapestry5.internal.OptionModelImpl;
021import org.apache.tapestry5.internal.SelectModelImpl;
022import org.apache.tapestry5.services.SelectModelFactory;
023import org.apache.tapestry5.services.ValueEncoderSource;
024import org.apache.tapestry5.services.ValueLabelProvider;
025
026import java.util.List;
027
028public class SelectModelFactoryImpl implements SelectModelFactory
029{
030    private final PropertyAccess propertyAccess;
031
032    private final ValueEncoderSource valueEncoderSource;
033
034    private final ValueLabelProvider<Object> valueLabelProvider;
035
036    public SelectModelFactoryImpl(PropertyAccess propertyAccess, ValueEncoderSource valueEncoderSource, ValueLabelProvider<Object> valueLabelProvider)
037    {
038        this.propertyAccess = propertyAccess;
039        this.valueEncoderSource = valueEncoderSource;
040        this.valueLabelProvider = valueLabelProvider;
041    }
042
043
044    public SelectModel create(List<?> objects, String labelProperty)
045    {
046        PropertyValueLabelProvider propertyValueLabelProvider = new PropertyValueLabelProvider(
047                valueEncoderSource, propertyAccess, labelProperty);
048
049        return createSelectModel(objects, propertyValueLabelProvider);
050    }
051
052    public SelectModel create(List<?> objects)
053    {
054        return createSelectModel(objects, valueLabelProvider);
055    }
056
057    private SelectModel createSelectModel(List<?> objects, ValueLabelProvider<Object> labelProvider)
058    {
059        final List<OptionModel> options = CollectionFactory.newList();
060
061        for (Object object : objects)
062        {
063            String label = labelProvider.getLabel(object);
064
065            options.add(new OptionModelImpl(label, object));
066        }
067
068        return new SelectModelImpl(null, options);
069    }
070}