OgnlCache.java

  1. /*
  2.  *    Copyright 2009-2024 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.  *       https://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.OgnlContext;
  21. import ognl.OgnlException;

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

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

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

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

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

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

  53. }