PageRenderTime 688ms CodeModel.GetById 81ms app.highlight 453ms RepoModel.GetById 81ms app.codeStats 2ms

/src/mpv5/utils/models/MPComboBoxModelItem.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 602 lines | 297 code | 50 blank | 255 comment | 58 complexity | 20c865df8db0c1f8643030cd9e69f84b MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *
  4 *  YaBS is free software: you can redistribute it and/or modify
  5 *  it under the terms of the GNU General Public License as published by
  6 *  the Free Software Foundation, either version 3 of the License, or
  7 *  (at your option) any later version.
  8 *
  9 *  YaBS is distributed in the hope that it will be useful,
 10 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *  GNU General Public License for more details.
 13 *
 14 *  You should have received a copy of the GNU General Public License
 15 *  along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.utils.models;
 18
 19import java.util.Arrays;
 20import java.util.List;
 21import java.util.Vector;
 22import javax.swing.ComboBoxModel;
 23import javax.swing.DefaultComboBoxModel;
 24import mpv5.db.common.DatabaseObject;
 25import mpv5.handler.MPEnum;
 26import mpv5.logging.Log;
 27
 28/**
 29 * A MPComboBoxModelItem consists of a visible "value" part and an invisible "ID" part.
 30 * 
 31 */
 32public class MPComboBoxModelItem extends DefaultComboBoxModel implements Comparable<MPComboBoxModelItem> {
 33
 34    private static final long serialVersionUID = 1L;
 35    public static int COMPARE_BY_ID = 0;
 36    /**
 37     * (default)
 38     */
 39    public static int COMPARE_BY_VALUE = 1;
 40    /**
 41     * The id field may have any class.
 42     */
 43    public Class ID_CLASS = String.class;
 44
 45    /**
 46     * Convenience method for Integer IDs. Returns the index of the item with the given id
 47     * @param uid
 48     * @param model
 49     * @return
 50     */
 51    public static int getItemID(Integer uid, ComboBoxModel model) {
 52        return getItemID((Object) new Integer(uid), model);
 53    }
 54
 55    /**
 56     * Returns the index of the item with the given id
 57     * @param uid
 58     * @param model
 59     * @return
 60     */
 61    public static int getItemID(Object uid, ComboBoxModel model) {
 62        for (int i = 0; i < model.getSize(); i++) {
 63//            Log.Debug(MPComboBoxModelItem.class, ((MPComboBoxModelItem) model.getElementAt(i)).id + " comparing with: " + uid);
 64            if (((MPComboBoxModelItem) model.getElementAt(i)).id.equals(uid)) {
 65//                Log.Debug(MPComboBoxModelItem.class, "Found at Index:" + i);
 66                return i;
 67            }
 68        }
 69        return -1;
 70    }
 71
 72    /**
 73     * Convenience method for String IDs. Returns the index of the item with the given id
 74     * @param uid
 75     * @param model
 76     * @return
 77     */
 78    public static int getItemID(String uid, ComboBoxModel model) {
 79        for (int i = 0; i < model.getSize(); i++) {
 80//            Log.Debug(MPComboBoxModelItem.class, ((MPComboBoxModelItem) model.getElementAt(i)).id + " comparing with: " + uid);
 81            if (((MPComboBoxModelItem) model.getElementAt(i)).id.toString().equals(uid)) {
 82//                Log.Debug(MPComboBoxModelItem.class, "Found at Index:" + i);
 83                return i;
 84            }
 85        }
 86        return 0;
 87    }
 88
 89    /**
 90     * Returns the index of the item with the given id
 91     * @param value
 92     * @param model
 93     * @return
 94     */
 95    public synchronized static int getItemIDfromValue(String value, ComboBoxModel model) {
 96        for (int i = 0; i < model.getSize(); i++) {
 97//            Log.Debug(MPComboBoxModelItem.class, ((MPComboBoxModelItem) model.getElementAt(i)).name + " comparing with: " + value);
 98            if (((MPComboBoxModelItem) model.getElementAt(i)).name.equals(value)) {
 99//                Log.Debug(MPComboBoxModelItem.class, "Found at Index:" + i);
100                return i;
101            }
102        }
103        return 0;
104    }
105
106    /**
107     * Converts an array to mp combo box items
108     * {id (hidden), value (shown in the list)}
109     * @param items
110     * @return
111     */
112    public static MPComboBoxModelItem[] toItems(Object[][] items) {
113        return toItems(items, COMPARE_BY_VALUE);
114    }
115
116    /**
117     * Converts an array to mp combo box items
118     * {id (hidden), values (shown in the list)}
119     * @param items
120     * @param compareMode
121     * @return
122     */
123    public static MPComboBoxModelItem[] toItems(Object[][] items, int compareMode) {
124        return toItems(items, compareMode, false);
125    }
126
127    /**
128     * Converts an array to mp combo box items
129     * {id (hidden), values (shown in the list)}
130     * @param items
131     * @param compareMode
132     * @param convertIndexToInteger
133     * @return
134     */
135    public static MPComboBoxModelItem[] toItems(Object[][] items, int compareMode, boolean convertIndexToInteger) {
136        MPComboBoxModelItem[] array = new MPComboBoxModelItem[items.length];
137        for (int i = 0; i < array.length; i++) {
138            String x = "";
139            for (int j = 1; j < items[i].length; j++) {
140                String k = String.valueOf(items[i][j]).trim();
141                x += k + " ";
142            }
143
144            if (convertIndexToInteger) {
145                array[i] = new MPComboBoxModelItem(Integer.valueOf(items[i][0].toString()), x.substring(0, x.length() - 1));
146            } else {
147                array[i] = new MPComboBoxModelItem((items[i][0]), x.substring(0, x.length() - 1));
148            }
149            array[i].setCompareMode(compareMode);
150        }
151        return array;
152    }
153
154    /**
155     * Converts an array to mp combo box items
156     * {id (hidden), values (shown in the list)}
157     * @param items
158     * @param compareMode
159     * @param formatString format _$value1$_ xx _$value2$_ etc.
160     * @return
161     */
162    public static MPComboBoxModelItem[] toItems(Object[][] items, int compareMode, String formatString) {
163        MPComboBoxModelItem[] array = new MPComboBoxModelItem[items.length];
164        String[] vaars = null;
165        if (formatString != null) {
166            vaars = formatString.split("_\\$");
167            Log.Debug(MPComboBoxModelItem.class, "Length of var string: " + vaars.length);
168        }
169        for (int i = 0; i < items.length; i++) {
170            String x = "";
171            String format = formatString;
172            for (int j = 1; j < items[i].length; j++) {
173                String k = String.valueOf(items[i][j]);
174                if (format == null) {
175                    x += k;
176                } else {
177                    try {
178                        format = format.replaceFirst("_\\$(.*?)\\$_", k);
179                    } catch (Exception e) {
180                        Log.Debug(e);
181                    }
182                    x = format;
183                }
184            }
185
186            array[i] = new MPComboBoxModelItem(items[i][0], x);
187            array[i].setCompareMode(compareMode);
188        }
189        return array;
190    }
191
192    /**
193     * Converts an array to mp combo box items
194     * {id (hidden), value (shown in the list)}
195     *
196     * @param items
197     * @param sortValuesNaturally If TRUE, sorts the Items into ascending order, according to the natural ordering of its values
198     * @return
199     */
200    public static MPComboBoxModelItem[] toItems(Object[][] items, boolean sortValuesNaturally) {
201        MPComboBoxModelItem[] array = toItems(items);
202        if (sortValuesNaturally) {
203            Arrays.sort(array);
204        }
205        return array;
206    }
207
208    /**
209     * Converts an array to mp combo box items
210     * {id (hidden), value (shown in the list)}
211     *
212     * @param items
213     * @param sortValuesNaturally If TRUE, sorts the Items into ascending order, according to the natural ordering of its values
214     * @param convertIndexToInteger
215     * @return
216     */
217    public static MPComboBoxModelItem[] toItems(Object[][] items, boolean sortValuesNaturally, boolean convertIndexToInteger) {
218        MPComboBoxModelItem[] array = toItems(items, COMPARE_BY_VALUE, convertIndexToInteger);
219        if (sortValuesNaturally) {
220            Arrays.sort(array);
221        }
222        return array;
223    }
224
225    /**
226     * Converts an array to mp combo box items
227     * {id (hidden), value (shown in the list)}
228     *
229     * @param items
230     * @param sortValuesNaturally If TRUE, sorts the Items into ascending order, according to the natural ordering of its values
231     * @param compareMode 
232     * @param format _$value1$_ xx _$value2$_ etc.
233     * @return
234     */
235    public static MPComboBoxModelItem[] toItems(Object[][] items, boolean sortValuesNaturally, int compareMode, String format) {
236        MPComboBoxModelItem[] array = toItems(items, compareMode, format);
237        if (sortValuesNaturally) {
238            Arrays.sort(array);
239        }
240
241//        Log.PrintArray(items);
242        return array;
243    }
244
245    /**
246     * Converts an array to mp combo box items
247     * {Integer id (hidden), String value (shown in the list)}
248     * @param items
249     * @return
250     */
251    public static MPComboBoxModelItem[] toItems(List<DatabaseObject> items) {
252        return toItems(items, COMPARE_BY_VALUE);
253    }
254
255    /**
256     * Converts an array to mp combo box items
257     * {Integer id (hidden), String value (shown in the list)}
258     * @param items
259     * @return
260     */
261    public static MPComboBoxModelItem[] toItems(List items, boolean simple) {
262        MPComboBoxModelItem[] array = new MPComboBoxModelItem[items.size()];
263        for (int i = 0; i < array.length; i++) {
264            array[i] = new MPComboBoxModelItem(items.get(i), items.get(i).toString());
265            array[i].setCompareMode(COMPARE_BY_VALUE);
266        }
267        return array;
268    }
269
270    /**
271     * Converts an array to mp combo box items
272     * {Integer id (hidden), String value (shown in the list)}
273     * @param items
274     * @param compareMode
275     * @return
276     */
277    public static MPComboBoxModelItem[] toItems(List<DatabaseObject> items, int compareMode) {
278        MPComboBoxModelItem[] array = new MPComboBoxModelItem[items.size()];
279        for (int i = 0; i < array.length; i++) {
280            array[i] = new MPComboBoxModelItem(new Integer(items.get(i).__getIDS()), items.get(i).__getCname());
281            array[i].setCompareMode(compareMode);
282        }
283        return array;
284    }
285
286    /**
287     * Converts an enum<id, name> to mp combo box items
288     * {id (hidden), value (shown in the list)}
289     * @param items
290     * @return
291     */
292    public static MPComboBoxModelItem[] toItems(MPEnum[] items) {
293        return toItems(items, COMPARE_BY_VALUE, new Vector<Integer>());
294    }
295
296    /**
297     * Converts an enum<id, name> to mp combo box items
298     * {id (hidden), value (shown in the list)}
299     * @param items
300     * @param compareMode
301     * @param skip
302     * @return
303     */
304    public static MPComboBoxModelItem[] toItems(MPEnum[] items, int compareMode, List<Integer> skip) {
305//        Log.PrintArray(items);
306        MPComboBoxModelItem[] array = new MPComboBoxModelItem[items.length - skip.size()];
307        for (int i = 0, z = 0; i < items.length; i++) {
308            if (!skip.contains(new Integer(i))) {
309                array[z] = new MPComboBoxModelItem(items[i].getId(), items[i].getName());
310                array[z].setCompareMode(compareMode);
311                z++;
312            }
313        }
314        return array;
315    }
316
317    /**
318     * Creates a {@link MPComBoxModel} containing an array of {@link MPComboBoxModelItem}
319     * {enum id (hidden), value (shown in the list)}
320     * @param data
321     * @return
322     */
323    public static MPComboboxModel toModel(MPEnum[] data) {
324        return new MPComboboxModel(toItems(data));
325    }
326
327    /**
328     * Creates a {@link MPComBoxModel} containing a {@link MPComboBoxModelItem}
329     * {ids (hidden), cname (shown in the list)}
330     * @param data
331     * @return
332     */
333    public static MPComboboxModel toModel(DatabaseObject data) {
334        return new MPComboboxModel(toItems(new Vector<DatabaseObject>(Arrays.asList(new DatabaseObject[]{data}))));
335    }
336
337    /**
338     * Creates a {@link MPComBoxModel} containing a {@link MPComboBoxModelItem}
339     * {entity (hidden), dbo (shown in the list)}
340     * @param <T>
341     * @param data
342     * @return
343     */
344    public static <T extends DatabaseObject> MPComboboxModel toModel0(List<T> data) {
345        Object[][] l = new Object[data.size()][2];
346        for (int i = 0; i < data.size(); i++) {
347            DatabaseObject databaseObject = data.get(i);
348            l[i][0] = databaseObject.IDENTITY;
349            l[i][0] = databaseObject;
350        }
351        return new MPComboboxModel(toItems(l));
352    }
353
354    /**
355     * Delegates to new MPComboboxModel(data);
356     * @param data
357     * @return
358     */
359    public static MPComboboxModel toModel(MPComboBoxModelItem[] data) {
360        return new MPComboboxModel(data);
361    }
362
363    /**
364     *  Creates a {@link DefaultComBoxModel} containing an array of {@link MPComboBoxModelItem}
365     * @param list
366     * @return
367     */
368    public static MPComboboxModel toModel(List<MPComboBoxModelItem> list) {
369        return new MPComboboxModel(list.toArray(new MPComboBoxModelItem[]{}));
370    }
371
372    /**
373     * Creates a {@link DefaultComBoxModel} containing an array of {@link MPComboBoxModelItem}
374     * {enum id (hidden), value (shown in the list)}
375     * @param data
376     * @param compareMode
377     * @param skip
378     * @return
379     */
380    public static MPComboboxModel toModel(MPEnum[] data, int compareMode, List<Integer> skip) {
381        return new MPComboboxModel(toItems(data, compareMode, skip));
382    }
383
384    /**
385     * Creates a {@link DefaultComBoxModel} containing an array of {@link MPComboBoxModelItem}
386     * {id (hidden), value (shown in the list)}
387     * @param data
388     * @return
389     */
390    public static MPComboboxModel toModel(Object[][] data) {
391        return new MPComboboxModel(toItems(data));
392    }
393    private Object id;
394    private String name;
395    private int comparemode = COMPARE_BY_VALUE;
396
397    /**
398     * Creates a new item with the given id and value
399     * @param id
400     * @param name
401     */
402    public MPComboBoxModelItem(Integer id, String name) {
403        this.id = id;
404        this.name = name;
405        this.ID_CLASS = id.getClass();
406    }
407
408    /**
409     * Creates a new item with the given id and value
410     * @param id
411     * @param name
412     */
413    public MPComboBoxModelItem(Object id, String name) {
414        this.id = id;
415        this.name = name;
416        this.ID_CLASS = id.getClass();
417    }
418
419    /**
420     * To determine the class of the ID field object
421     * @return A class
422     */
423    public Class getIDClass() {
424        return ID_CLASS;
425    }
426
427    /**
428     * Creates a new instance of the class represented by this items' ID Class object.
429     * The class is instantiated as if by a new expression with an empty argument list.
430     *
431     * @return An Object or null if the ID class has no public empty constructor
432     */
433    public Object getInstanceOfIDClass() {
434        try {
435            return getIDClass().newInstance();
436        } catch (InstantiationException ex) {
437            mpv5.logging.Log.Debug(ex);//Logger.getLogger(MPComboBoxModelItem.class.getName()).log(Level.SEVERE, null, ex);
438        } catch (IllegalAccessException ex) {
439            mpv5.logging.Log.Debug(ex);//Logger.getLogger(MPComboBoxModelItem.class.getName()).log(Level.SEVERE, null, ex);
440        }
441        return null;
442    }
443
444    /**
445     * The String value of the ID field
446     * @return A {@link String} representation of this items' ID Object - <b>NEVER<b/> null
447     */
448    public String getId() {
449        return String.valueOf(id);
450    }
451
452    /**
453     * The ID field
454     * @return the id Object
455     */
456    public Object getIdObject() {
457        return id;
458    }
459
460    /**
461     * If the id is greater than 0 or longer than 0 if a String index or non-null for other ID Objects
462     * @return true if the ID appears to be valid as defined above.
463     */
464    public boolean isValid() {
465        if (id != null) {
466            try {
467                if (Integer.valueOf(id.toString()).intValue() > 0) {
468                    return true;
469                } else {
470                    return false;
471                }
472            } catch (NumberFormatException numberFormatException) {
473                if (id instanceof String && ((String) id).length() > 0) {
474                    return true;
475                } else {
476                    return false;
477                }
478            }
479        } else {
480            return false;
481        }
482    }
483
484    /**
485     * Define how the items compare to each other
486     * @param mode
487     */
488    public void setCompareMode(int mode) {
489        this.comparemode = mode;
490    }
491
492    /**
493    
494     * @param id the id to set
495     */
496    public void setId(Integer id) {
497        this.id = id;
498    }
499
500    /**
501     * Define the ID field of this item
502     * @param id the id to set
503     */
504    public void setId(Object id) {
505        this.id = id;
506    }
507
508    /**
509     * @return the value
510     */
511    public String getValue() {
512        return name;
513    }
514
515    /**
516     * Delegates to {@link MPComboBoxModelItem#setValue(String)}
517     * @param name the name to set
518     */
519    public void setName(String name) {
520        this.name = name;
521    }
522
523    /**
524     * Sets the displayed value of this item
525     * @param value
526     */
527    public void setValue(String value) {
528        this.name = value;
529    }
530
531    /**
532     * Returns the value of the item
533     */
534    @Override
535    public String toString() {
536        return name != null && !"".equals(name) ? name : "";
537    }
538
539//     * <br/>The ID field is <b>NOT</b> part of the compare.
540//     *
541//     * Note: this class has a natural ordering that is inconsistent with equals.
542    /**
543     * MPComboBoxModelItems are compared to their ids and values!
544     * @param to 
545     */
546    @Override
547    public int compareTo(MPComboBoxModelItem to) {
548        final int EQUAL = 0;
549        if (this == to) {
550            return EQUAL;
551        }
552        if (to.getIdObject().equals(id) && to.getValue().equals(getValue())) {
553            return EQUAL;
554        }
555
556        if (comparemode == COMPARE_BY_VALUE) {
557            int comparison = this.getValue().compareTo(to.getValue());
558            if (comparison != EQUAL) {
559                return comparison;
560            }
561            comparison = this.getId().compareTo(to.getId());
562            if (comparison != EQUAL) {
563                return comparison;
564            }
565        } else {
566            int comparison = this.getId().compareTo(to.getId());
567            if (comparison != EQUAL) {
568                return comparison;
569            }
570            comparison = this.getValue().compareTo(to.getValue());
571            if (comparison != EQUAL) {
572                return comparison;
573            }
574        }
575
576        assert this.equals(to) : "compareTo inconsistent with equals.";
577        return EQUAL;
578    }
579
580    @Override
581    public boolean equals(Object anotherObject) {
582        if (anotherObject == null || !(anotherObject instanceof MPComboBoxModelItem)) {
583            return false;
584        }
585
586        MPComboBoxModelItem mPComboBoxModelItem = (MPComboBoxModelItem) anotherObject;
587
588        if (mPComboBoxModelItem.getIdObject().equals(id) && mPComboBoxModelItem.getValue().equals(getValue())) {
589            return true;
590        } else {
591            return false;
592        }
593    }
594
595    @Override
596    public int hashCode() {
597        int hash = 7;
598        hash = 29 * hash + (this.id != null ? this.id.hashCode() : 0);
599        hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0);
600        return hash;
601    }
602}