001    package org.gwtbootstrap3.extras.typeahead.client.base;
002    
003    /*
004     * #%L
005     * GwtBootstrap3
006     * %%
007     * Copyright (C) 2013 - 2014 GwtBootstrap3
008     * %%
009     * Licensed under the Apache License, Version 2.0 (the "License");
010     * you may not use this file except in compliance with the License.
011     * You may obtain a copy of the License at
012     * 
013     *      http://www.apache.org/licenses/LICENSE-2.0
014     * 
015     * Unless required by applicable law or agreed to in writing, software
016     * distributed under the License is distributed on an "AS IS" BASIS,
017     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018     * See the License for the specific language governing permissions and
019     * limitations under the License.
020     * #L%
021     */
022    
023    import java.util.ArrayList;
024    import java.util.Collection;
025    
026    /**
027     * A Dataset operating on a collection of values.
028     *
029     * @author Florian Kremser <florian.kremser@sage.com>
030     */
031    public class CollectionDataset<T> extends Dataset<T> {
032        private Collection<T> data;
033    
034        public CollectionDataset(final Collection<T> data) {
035            setData(data);
036        }
037    
038        public Collection<T> getData() {
039            return data;
040        }
041    
042        public void setData(final Collection<T> data) {
043            this.data = data;
044        }
045    
046        /**
047         * Return the (display) value associated with a particular datum. If the
048         * given datum is selected from the suggestions, then value will be set as
049         * text of the input.
050         *
051         * @param datum a datum instance from this {@link Dataset}
052         * @return the text representing the data
053         */
054        public String getValue(final T datum) {
055            return datum != null ? datum.toString() : "";
056        }
057    
058        @Override
059        public void findMatches(final String query, final SuggestionCallback<T> callback) {
060            String queryLower = query.toLowerCase();
061            Collection<Suggestion<T>> suggestions = new ArrayList<Suggestion<T>>();
062            if (data != null) {
063                  for (T datum : data) {
064                      String value = getValue(datum);
065                          if (value.toLowerCase().contains(queryLower)) {
066                              Suggestion<T> suggestion = Suggestion.create(value, datum, this);
067                              suggestions.add(suggestion);
068                          }
069                  }
070            }
071            callback.execute(suggestions);
072        }
073    }