View Javadoc

1   /*
2    * $Id: PreferredObjectSelector.java 21835 2011-05-06 18:05:08Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.config;
12  
13  import java.util.Comparator;
14  import java.util.Iterator;
15  
16  /**
17   * Selects a preferred object from a collection of instances of the same type
18   * based on the weight of the {@link Preferred} annotation. If there is no
19   * preferred instances, then it just returns the first object in the collection.
20   */
21  public class PreferredObjectSelector<T>
22  {
23  
24      private final Comparator<T> comparator;
25  
26      public PreferredObjectSelector()
27      {
28          comparator = new Comparator<T>()
29          {
30              private PreferredComparator preferredComparator = new PreferredComparator();
31  
32              public int compare(T candidate1, T candidate2)
33              {
34                  final Preferred preferred = candidate1.getClass().getAnnotation(Preferred.class);
35                  final Preferred preferred1 = candidate2.getClass().getAnnotation(Preferred.class);
36  
37                  return preferredComparator.compare(preferred, preferred1);
38              }
39          };
40      }
41  
42      /**
43       * Selects a preferred object from instances returned by an {@link Iterator}.
44       * <p/>
45       * The preferred instance will be the instance annotated with {@link Preferred}
46       * annotation with the highest weight attribute if there is any, or a non
47       * annotated class otherwise.
48       *
49       * @param iterator contains the objects to select from
50       * @return the preferred instance
51       */
52      public T select(Iterator<T> iterator)
53      {
54          T preferred = null;
55  
56          if (iterator.hasNext())
57          {
58              preferred = iterator.next();
59  
60              while (iterator.hasNext())
61              {
62                  T current = iterator.next();
63  
64                  if (comparator.compare(preferred, current) == -1)
65                  {
66                      preferred = current;
67                  }
68              }
69          }
70  
71          return preferred;
72      }
73  }