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