1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jxpath;
18
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25
26
27
28
29
30
31
32
33
34
35 public class FunctionLibrary implements Functions {
36 private final List allFunctions = new ArrayList();
37 private Map byNamespace;
38
39
40
41
42
43 public void addFunctions(Functions functions) {
44 allFunctions.add(functions);
45 synchronized (this) {
46 byNamespace = null;
47 }
48 }
49
50
51
52
53
54 public void removeFunctions(Functions functions) {
55 allFunctions.remove(functions);
56 synchronized (this) {
57 byNamespace = null;
58 }
59 }
60
61
62
63
64
65
66 public Set getUsedNamespaces() {
67 return functionCache().keySet();
68 }
69
70
71
72
73
74
75
76
77
78 public Function getFunction(String namespace, String name,
79 Object[] parameters) {
80 Object candidates = functionCache().get(namespace);
81 if (candidates instanceof Functions) {
82 return ((Functions) candidates).getFunction(
83 namespace,
84 name,
85 parameters);
86 }
87 if (candidates instanceof List) {
88 List list = (List) candidates;
89 int count = list.size();
90 for (int i = 0; i < count; i++) {
91 Function function =
92 ((Functions) list.get(i)).getFunction(
93 namespace,
94 name,
95 parameters);
96 if (function != null) {
97 return function;
98 }
99 }
100 }
101 return null;
102 }
103
104
105
106
107
108 private synchronized Map functionCache() {
109 if (byNamespace == null) {
110 byNamespace = new HashMap();
111 int count = allFunctions.size();
112 for (int i = 0; i < count; i++) {
113 Functions funcs = (Functions) allFunctions.get(i);
114 Set namespaces = funcs.getUsedNamespaces();
115 for (Iterator it = namespaces.iterator(); it.hasNext();) {
116 String ns = (String) it.next();
117 Object candidates = byNamespace.get(ns);
118 if (candidates == null) {
119 byNamespace.put(ns, funcs);
120 }
121 else if (candidates instanceof Functions) {
122 List lst = new ArrayList();
123 lst.add(candidates);
124 lst.add(funcs);
125 byNamespace.put(ns, lst);
126 }
127 else {
128 ((List) candidates).add(funcs);
129 }
130 }
131 }
132 }
133 return byNamespace;
134 }
135 }