Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
PreferredObjectSelector |
|
| 0.0;0 | ||||
PreferredObjectSelector$1 |
|
| 0.0;0 |
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 | 0 | { |
24 | 0 | comparator = new Comparator<T>() |
25 | 0 | { |
26 | 0 | private PreferredComparator preferredComparator = new PreferredComparator(); |
27 | ||
28 | public int compare(T threadPoolFactory, T threadPoolFactory1) | |
29 | { | |
30 | 0 | final Preferred preferred = threadPoolFactory.getClass().getAnnotation(Preferred.class); |
31 | 0 | final Preferred preferred1 = threadPoolFactory1.getClass().getAnnotation(Preferred.class); |
32 | ||
33 | 0 | return preferredComparator.compare(preferred, preferred1); |
34 | } | |
35 | }; | |
36 | 0 | } |
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 | 0 | T preferred = null; |
51 | ||
52 | 0 | if (iterator.hasNext()) |
53 | { | |
54 | 0 | preferred = iterator.next(); |
55 | ||
56 | 0 | while (iterator.hasNext()) |
57 | { | |
58 | 0 | T current = iterator.next(); |
59 | ||
60 | 0 | if (comparator.compare(preferred, current) == -1) |
61 | { | |
62 | 0 | preferred = current; |
63 | } | |
64 | 0 | } |
65 | } | |
66 | ||
67 | 0 | return preferred; |
68 | } | |
69 | } |