KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > scriptella > driver > xpath > XPathExpressionCompiler


1 /*
2  * Copyright 2006-2007 The Scriptella Project Team.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 JavaDoc;
21 import javax.xml.xpath.XPathExpressionException JavaDoc;
22 import javax.xml.xpath.XPathFactory JavaDoc;
23 import java.util.Map JavaDoc;
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 JavaDoc XPATH_FACTORY = XPathFactory.newInstance();
35     private Map<String JavaDoc, XPathExpression JavaDoc> cache = new LRUMap<String JavaDoc, XPathExpression JavaDoc>(DEFAULT_SIZE);
36
37     public XPathExpression JavaDoc compile(final String JavaDoc expression) {
38         String JavaDoc trimmedEx = expression.trim();
39         XPathExpression JavaDoc ex = cache.get(trimmedEx);
40         if (ex == null) {
41             try {
42                 cache.put(trimmedEx, ex = XPATH_FACTORY.newXPath().compile(trimmedEx));
43             } catch (XPathExpressionException JavaDoc e) {
44                 throw new XPathProviderException("Unable to compile XPath query: " + trimmedEx, e);
45             }
46         }
47         return ex;
48     }
49 }
50
Popular Tags