View Javadoc
1   package net.sumaris.core.extraction.dao.technical.xml;
2   
3   /*-
4    * #%L
5    * SUMARiS:: Core Extraction
6    * %%
7    * Copyright (C) 2018 - 2019 SUMARiS Consortium
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/gpl-3.0.html>.
22   * #L%
23   */
24  
25  import com.google.common.collect.Maps;
26  import org.jdom2.filter.Filter;
27  import org.jdom2.xpath.XPathExpression;
28  import org.jdom2.xpath.XPathFactory;
29  
30  import java.util.List;
31  import java.util.Map;
32  
33  /**
34   * @author Benoit Lavenier <benoit.lavenier@e-is.pro>*
35   */
36  public class XPaths {
37  
38      private static final ThreadLocal<XPathFactory> factoryMapper = ThreadLocal.withInitial(XPathFactory::instance);
39  
40      private static final ThreadLocal<Map<String, XPathExpression<?>>> expressionMapper = ThreadLocal.withInitial(Maps::newHashMap);
41  
42      public static XPathFactory getThreadXPathFactory() {
43          return factoryMapper.get();
44      }
45  
46      public static <T> XPathExpression<T> compile(String expression, Filter<T> filter) {
47          Map<String, XPathExpression<?>> expressionMap = expressionMapper.get();
48          XPathExpression<?> xpathExpression = expressionMap.get(expressionMap);
49          if (xpathExpression == null) {
50              xpathExpression = getThreadXPathFactory().compile(expression, filter);
51              expressionMap.put(expression, xpathExpression);
52          }
53          return (XPathExpression<T>)xpathExpression;
54      }
55  
56      public static <T> List<T> evaluate(String expression, Filter<T> filter, Object object) {
57          return compile(expression, filter).evaluate(object);
58      }
59  
60      public static <T> T evaluateFirst(String expression, Filter<T> filter, Object object) {
61          return compile(expression, filter).evaluateFirst(object);
62      }
63  }