KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > cintoo > messages > context > DefaultContextMap


1 package cintoo.messages.context;
2
3 import api.cintoo.messages.context.Context;
4 import api.cintoo.messages.context.ContextMap;
5
6 import java.util.*;
7
8 public class DefaultContextMap implements ContextMap {
9   private Map<Context, String JavaDoc> map;
10   private List<Context> sortedContexts;
11
12   public DefaultContextMap() {
13     map = new HashMap<Context, String JavaDoc>();
14     // we need to sort bundle contexts
15
// the most specific context should be
16
// first. HashMap does not support sorting
17
// and TreeMap does not support entries which
18
// compare to 0
19
sortedContexts = new ArrayList<Context>();
20   }
21
22   public void put(Context context, String JavaDoc bundleName) {
23     map.put(context, bundleName);
24     sortedContexts.add(context);
25     Collections.<Context>sort(sortedContexts);
26   }
27
28   public String JavaDoc get(Context context) {
29     return map.get(context);
30   }
31
32   public Context findMatchingContext(Context context) {
33     for (Context bundleContext : sortedContexts) {
34       if (bundleContext.matches(context)) {
35         return bundleContext;
36       }
37     }
38     return null;
39   }
40
41   public void clear() {
42     if (map != null) {
43       map.clear();
44     }
45     if (null != sortedContexts) {
46       sortedContexts.clear();
47     }
48   }
49
50   public Context findParentContext(Context context) {
51     int size = sortedContexts.size();
52     int index = findContext(context);
53
54     for (int i = index + 1; i < size; i++) {
55       Context parentContext = sortedContexts.get(i);
56       if (parentContext.getClass() == context.getClass() && parentContext.matches(context)) {
57         return parentContext;
58       }
59     }
60     return null;
61   }
62
63   public Context findChildContext(Context context) {
64     int size = sortedContexts.size();
65     int index = findContext(context);
66
67     for (int i = index - 1; i >= 0; i--) {
68       Context childContext = sortedContexts.get(i);
69       if (childContext.getClass() == context.getClass() && context.matches(childContext)) {
70         return childContext;
71       }
72     }
73     return null;
74   }
75
76   private int findContext(Context context) {
77     int size = sortedContexts.size();
78     for (int i = 0; i < size; i++) {
79       Context childContext = sortedContexts.get(i);
80       if (childContext.equals(context)) {
81         return i;
82       }
83     }
84     return -1;
85   }
86 }
87
Popular Tags