01: /*
02: * Copyright 2006-2007 The Scriptella Project Team.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package scriptella.driver.xpath;
17:
18: import scriptella.util.LRUMap;
19:
20: import javax.xml.xpath.XPathExpression;
21: import javax.xml.xpath.XPathExpressionException;
22: import javax.xml.xpath.XPathFactory;
23: import java.util.Map;
24:
25: /**
26: * Represents a facade for compiling xpath expressions.
27: * <p>Expressions caching is also supported.
28: *
29: * @author Fyodor Kupolov
30: * @version 1.0
31: */
32: class XPathExpressionCompiler {
33: private static final int DEFAULT_SIZE = 100;
34: private static final XPathFactory XPATH_FACTORY = XPathFactory
35: .newInstance();
36: private Map<String, XPathExpression> cache = new LRUMap<String, XPathExpression>(
37: DEFAULT_SIZE);
38:
39: public XPathExpression compile(final String expression) {
40: String trimmedEx = expression.trim();
41: XPathExpression ex = cache.get(trimmedEx);
42: if (ex == null) {
43: try {
44: cache.put(trimmedEx, ex = XPATH_FACTORY.newXPath()
45: .compile(trimmedEx));
46: } catch (XPathExpressionException e) {
47: throw new XPathProviderException(
48: "Unable to compile XPath query: " + trimmedEx,
49: e);
50: }
51: }
52: return ex;
53: }
54: }
|