]> git.argeo.org Git - gpl/argeo-suite.git/blob - api/RankedObject.java
Prepare next development cycle
[gpl/argeo-suite.git] / api / RankedObject.java
1 package org.argeo.app.api;
2
3 import java.util.Map;
4
5 import org.argeo.api.cms.CmsLog;
6
7 /**
8 * A container for an object whose relevance can be ranked. Typically used in an
9 * OSGi context with the service.ranking property.
10 */
11 public class RankedObject<T> {
12 private final static CmsLog log = CmsLog.getLog(RankedObject.class);
13
14 private final static String SERVICE_RANKING = "service.ranking";
15 // private final static String SERVICE_ID = "service.id";
16
17 private T object;
18 private Map<String, Object> properties;
19 private final Long rank;
20
21 public RankedObject(T object, Map<String, Object> properties) {
22 this(object, properties, extractRanking(properties));
23 }
24
25 public RankedObject(T object, Map<String, Object> properties, Long rank) {
26 super();
27 this.object = object;
28 this.properties = properties;
29 this.rank = rank;
30 }
31
32 private static Long extractRanking(Map<String, Object> properties) {
33 if (properties == null)
34 return 0l;
35 if (properties.containsKey(SERVICE_RANKING))
36 return Long.valueOf(properties.get(SERVICE_RANKING).toString());
37 // else if (properties.containsKey(SERVICE_ID))
38 // return (Long) properties.get(SERVICE_ID);
39 else
40 return 0l;
41 }
42
43 public T get() {
44 return object;
45 }
46
47 public Map<String, Object> getProperties() {
48 return properties;
49 }
50
51 public Long getRank() {
52 return rank;
53 }
54
55 @Override
56 public int hashCode() {
57 return object.hashCode();
58 }
59
60 @Override
61 public boolean equals(Object obj) {
62 if (!(obj instanceof RankedObject))
63 return false;
64 RankedObject<?> other = (RankedObject<?>) obj;
65 return rank.equals(other.rank) && object.equals(other.object);
66 }
67
68 @Override
69 public String toString() {
70 return object.getClass().getName() + " with rank " + rank;
71 }
72
73 public static <K, T> RankedObject<T> putIfHigherRank(Map<K, RankedObject<T>> map, K key, T object,
74 Map<String, Object> properties) {
75 RankedObject<T> rankedObject = new RankedObject<>(object, properties);
76 if (!map.containsKey(key)) {
77 map.put(key, rankedObject);
78 if (log.isTraceEnabled())
79 log.trace(
80 "Added " + key + " as " + object.getClass().getName() + " with rank " + rankedObject.getRank());
81 return rankedObject;
82 } else {
83 RankedObject<T> current = map.get(key);
84 if (current.getRank() <= rankedObject.getRank()) {
85 map.put(key, rankedObject);
86 if (log.isTraceEnabled())
87 log.trace("Replaced " + key + " by " + object.getClass().getName() + " with rank "
88 + rankedObject.getRank());
89 return rankedObject;
90 } else {
91 return current;
92 }
93 }
94
95 }
96
97 }