1 33 34 package com.icesoft.icefaces.samples.showcase.components.autocomplete; 35 36 import com.icesoft.faces.component.selectinputtext.SelectInputText; 37 import org.apache.commons.logging.Log; 38 import org.apache.commons.logging.LogFactory; 39 40 import javax.faces.event.ValueChangeEvent; 41 import javax.faces.model.SelectItem; 42 import java.util.ArrayList ; 43 import java.util.Collections ; 44 import java.util.Iterator ; 45 import java.util.List ; 46 47 54 public class AutoCompleteBean { 55 56 private static Log log = LogFactory.getLog(AutoCompleteBean.class); 57 58 private static List dictionary; 60 61 62 private City currentCity = new City("", "", "", "", "", "", 0); 64 65 private List matchesList = new ArrayList (); 67 68 74 public void updateList(ValueChangeEvent event) { 75 76 setMatches(event); 78 79 if (event.getComponent() instanceof SelectInputText) { 81 SelectInputText autoComplete = 82 (SelectInputText) event.getComponent(); 83 if (autoComplete.getSelectedItem() != null) { 85 currentCity = (City) autoComplete.getSelectedItem().getValue(); 86 } 87 else { 89 City tempCity = getMatch(autoComplete.getValue().toString()); 90 if (tempCity != null) { 91 currentCity = tempCity; 92 } 93 } 94 } 95 } 96 97 102 public City getCurrentCity() { 103 return currentCity; 104 } 105 106 111 public List getList() { 112 return matchesList; 113 } 114 115 private City getMatch(String value) { 116 City result = null; 117 if (matchesList != null) { 118 SelectItem si; 119 Iterator iter = matchesList.iterator(); 120 while (iter.hasNext()) { 121 si = (SelectItem) iter.next(); 122 if (value.equals(si.getLabel())) { 123 result = (City) si.getValue(); 124 } 125 } 126 } 127 return result; 128 } 129 130 131 public List getDictionary() { 132 return dictionary; 133 } 134 135 public void setDictionary(List dictionary) { 136 AutoCompleteBean.dictionary = dictionary; 137 } 138 139 145 private void setMatches(ValueChangeEvent event) { 146 147 Object searchWord = event.getNewValue(); 148 int maxMatches = ((SelectInputText) event.getComponent()).getRows(); 149 List matchList = new ArrayList (maxMatches); 150 151 try { 152 153 int insert = Collections.binarySearch(dictionary, searchWord, 154 AutoCompleteDictionary.LABEL_COMPARATOR); 155 156 if (insert < 0) { 158 insert = Math.abs(insert) - 1; 159 } 160 161 for (int i = 0; i < maxMatches; i++) { 162 if ((insert + i) >= dictionary.size() || 165 i >= maxMatches) { 166 break; 167 } 168 matchList.add(dictionary.get(insert + i)); 169 } 170 } catch (Throwable e) { 171 log.error("Erorr finding autocomplete matches", e); 172 } 173 if (this.matchesList != null) { 175 this.matchesList.clear(); 176 this.matchesList = null; 177 } 178 this.matchesList = matchList; 179 } 180 } | Popular Tags |