OgnlCache.java

  1. /*
  2.  *    Copyright 2009-2021 the original author or authors.
  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 org.apache.ibatis.scripting.xmltags;

  17. import java.util.Map;
  18. import java.util.concurrent.ConcurrentHashMap;

  19. import ognl.Ognl;
  20. import ognl.OgnlException;

  21. import org.apache.ibatis.builder.BuilderException;

  22. /**
  23.  * Caches OGNL parsed expressions.
  24.  *
  25.  * @author Eduardo Macarron
  26.  *
  27.  * @see <a href='https://github.com/mybatis/old-google-code-issues/issues/342'>Issue 342</a>
  28.  */
  29. public final class OgnlCache {

  30.   private static final OgnlMemberAccess MEMBER_ACCESS = new OgnlMemberAccess();
  31.   private static final OgnlClassResolver CLASS_RESOLVER = new OgnlClassResolver();
  32.   private static final Map<String, Object> expressionCache = new ConcurrentHashMap<>();

  33.   private OgnlCache() {
  34.     // Prevent Instantiation of Static Class
  35.   }

  36.   public static Object getValue(String expression, Object root) {
  37.     try {
  38.       Map context = Ognl.createDefaultContext(root, MEMBER_ACCESS, CLASS_RESOLVER, null);
  39.       return Ognl.getValue(parseExpression(expression), context, root);
  40.     } catch (OgnlException e) {
  41.       throw new BuilderException("Error evaluating expression '" + expression + "'. Cause: " + e, e);
  42.     }
  43.   }

  44.   private static Object parseExpression(String expression) throws OgnlException {
  45.     Object node = expressionCache.get(expression);
  46.     if (node == null) {
  47.       node = Ognl.parseExpression(expression);
  48.       expressionCache.put(expression, node);
  49.     }
  50.     return node;
  51.   }

  52. }