PropertyValueNavigator.java

  1. package com.gh.mygreen.xlsmapper.util;

  2. import java.lang.reflect.Field;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5. import java.util.Collection;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.concurrent.ConcurrentHashMap;

  9. import com.gh.mygreen.xlsmapper.util.PropertyPath.Token;


  10. /**
  11.  * プロパティにアクセスするためのクラス。
  12.  * <p>プロパティは式言語の形式に似た形式をとることが可能で、フィールドにもアクセスできます。</p>
  13.  *
  14.  * <h3 class="description">基本的な使い方</h3>
  15.  *
  16.  * <pre class="highlight"><code class="java">
  17.  * // Beanのインスタンスの生成
  18.  * Person taregetObj = ...;
  19.  *
  20.  * // 名前を指定してプロパティにアクセスする場合
  21.  * String name = PropertyValueNavigator.getProperty(targetObj, "name");
  22.  *
  23.  * // ネストしたプロパティにアクセスする場合、ピリオド(.)で繋げます。
  24.  * String code = PropertyValueNavigator.getProperty(targetObj, "county.code");
  25.  *
  26.  * // リストまたは配列にアクセスする場合、括弧[インデックス番号]でインデックスを指定します。
  27.  * String title = PropertyValueNavigator.getProperty(targetObj, "books[0].title");
  28.  *
  29.  * // マップにアクセスする場合、括弧[キー]でキーを指定します。
  30.  * String motherName = PropertyValueNavigator.getProperty(targetObj, "family[mother].name");
  31.  * </code></pre>
  32.  *
  33.  * <h3 class="description">オプションの指定</h3>
  34.  * <p>オプションを指定する場合は、PropertyNavigatorのインスタンスを生成し、設定します。
  35.  *
  36.  * <pre class="highlight"><code class="java">
  37.  * PropertyValueNavigator navigator = new PropertyValueNavigator();
  38.  *
  39.  * // 非公開のプロパティにアクセス可能かどうか
  40.  * navigator.setAllowPrivate(true);
  41.  *
  42.  * // 値がnullの場合に例外をスローしないでその時点で処理を終了するかどうか。
  43.  * navigator.setIgnoreNull(true);
  44.  *
  45.  * // 配列/Collection/Mapにアクセスする際に指定したキーの要素が存在しない場合に処理を終了するかどうか。
  46.  * navigator.setIgnoreNotFoundKey(true);
  47.  *
  48.  * // プロパティの解析結果をキャッシュするかどうか。途中の解析結果をキャッシュして、処理を高速化します。
  49.  * navigator.setCacheWithPath(true);
  50.  * </code></pre>
  51.  *
  52.  * @since 1.0
  53.  * @author T.TSUCHIE
  54.  *
  55.  */
  56. public class PropertyValueNavigator {

  57.     /**
  58.      * 非公開のプロパティにアクセス可能かどうか。
  59.      */
  60.     private boolean allowPrivate;

  61.     /**
  62.      * 値がnullの場合に例外をスローしないでその時点で処理を終了するかどうか。
  63.      */
  64.     private boolean ignoreNull;

  65.     /**
  66.      * 配列/Collection/Mapにアクセスする際に指定したキーの要素が存在しない場合に処理を終了するかどうか。
  67.      */
  68.     private boolean ignoreNotFoundKey;

  69.     /**
  70.      * プロパティの解析結果をキャッシュするかどうか。
  71.      */
  72.     private boolean cacheWithPath;

  73.     /**
  74.      * プロパティの式を解析して、トークンに分解するクラス。
  75.      */
  76.     private final PropertyPathTokenizer tokenizer = new PropertyPathTokenizer();

  77.     /**
  78.      * プロパティの解析結果をキャッシュデータ
  79.      */
  80.     private final Map<String, PropertyPath> cacheData = new ConcurrentHashMap<>();

  81.     /**
  82.      * プロパティの値を取得する。
  83.      * <p>オプションはデフォルト値で処理する。</p>
  84.      * @param obj 取得元となるオブジェクト。
  85.      * @param property プロパティ名。
  86.      * @return
  87.      * @throws IllegalArgumentException peropety is null or empty.
  88.      * @throws PropertyAccessException 存在しないプロパティを指定した場合など。
  89.      * @throws NullPointerException アクセスしようとしたプロパティがnullの場合。
  90.      * @throws IndexOutOfBoundsException リスト、配列にアクセスする際に存在しないインデックスにアクセスした場合。
  91.      * @throws IllegalStateException マップにアクセスする際に存在しないキーにアクセスした場合。
  92.      */
  93.     public static Object get(final Object obj, final String property) {
  94.         return new PropertyValueNavigator().getProperty(obj, property);
  95.     }

  96.     /**
  97.      * デフォルトコンストラクタ
  98.      */
  99.     public PropertyValueNavigator() {

  100.     }

  101.     /**
  102.      * プロパティの値を取得する。
  103.      *
  104.      * @param obj 取得元となるオブジェクト。
  105.      * @param property プロパティの式。
  106.      * @return プロパティの値。
  107.      * @throws IllegalArgumentException peropety is null or empty.
  108.      * @throws PropertyAccessException 存在しないプロパティを指定した場合など。
  109.      * @throws NullPointerException アクセスしようとしたプロパティがnullの場合。
  110.      *         ただし、オプション ignoreNull = falseのとき。
  111.      * @throws IndexOutOfBoundsException リスト、配列にアクセスする際に存在しないインデックスにアクセスした場合。
  112.      *         ただし、オプションignoreNotFoundKey = falseのとき。
  113.      * @throws IllegalStateException マップにアクセスする際に存在しないキーにアクセスした場合。
  114.      *         ただし、オプションignoreNotFoundKey = falseのとき。
  115.      */
  116.     public Object getProperty(final Object obj, final String property) {

  117.         ArgUtils.notEmpty(property, "property");

  118.         final PropertyPath path = parseProperty(property);
  119.         Object targetObj = obj;
  120.         for(Token token : path.getPathAsToken()) {

  121.             targetObj = accessProperty(targetObj, token);
  122.             if(targetObj == null && ignoreNull) {
  123.                 return null;
  124.             }

  125.         }
  126.         return targetObj;

  127.     }

  128.     private PropertyPath parseProperty(final String property) {

  129.         if(isCacheWithPath()) {
  130.             return cacheData.computeIfAbsent(property, k -> tokenizer.parse(property));
  131.         } else {
  132.             return tokenizer.parse(property);
  133.         }

  134.     }

  135.     /**
  136.      * 今までのキャッシュデータをクリアする。
  137.      */
  138.     public void clearCache() {
  139.         this.cacheData.clear();
  140.     }

  141.     private Object accessProperty(final Object targetObj, final Token token) {

  142.         if(token instanceof Token.Separator) {
  143.             return accessPropertyBySeparator(targetObj, (Token.Separator)token);

  144.         } else if(token instanceof Token.Name) {
  145.             return accessPropertyByName(targetObj, (Token.Name)token);

  146.         } else if(token instanceof Token.Key) {
  147.             return accessPropertyByKey(targetObj, (Token.Key)token);
  148.         }

  149.         throw new IllegalStateException("not support token type : " + token.getValue());

  150.     }

  151.     private Object accessPropertyBySeparator(final Object targetObj, final Token.Separator token) {

  152.         return targetObj;

  153.     }

  154.     private Object accessPropertyByName(final Object targetObj, final Token.Name token) {

  155.         if(targetObj == null) {
  156.             if(ignoreNull) {
  157.                 return null;
  158.             } else {
  159.                 throw new NullPointerException("access object is null. property name = " + token.getValue());
  160.             }

  161.         }

  162.         final Class<?> targetClass = targetObj.getClass();

  163.         // メソッドアクセス
  164.         final String getterMethodName = "get" + Utils.capitalize(token.getValue());
  165.         try {
  166.             Method getterMethod = allowPrivate ?
  167.                     targetClass.getDeclaredMethod(getterMethodName) : targetClass.getMethod(getterMethodName);
  168.             getterMethod.setAccessible(true);

  169.             return getterMethod.invoke(targetObj);

  170.         } catch (NoSuchMethodException | SecurityException e) {
  171.             // not found method

  172.         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  173.             // 値の取得に失敗
  174.             throw new PropertyAccessException("fail access method property : " + token.getValue(), e);
  175.         }

  176.         // boolean用メソッドアクセス
  177.         final String booleanMethodName = "is" + Utils.capitalize(token.getValue());
  178.         try {
  179.             Method getterMethod = allowPrivate ?
  180.                     targetClass.getDeclaredMethod(booleanMethodName) : targetClass.getMethod(booleanMethodName);;
  181.             getterMethod.setAccessible(true);

  182.             return getterMethod.invoke(targetObj);

  183.         } catch (NoSuchMethodException | SecurityException e) {
  184.             // not found method

  185.         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  186.             // 値の取得に失敗
  187.             throw new PropertyAccessException("fail access boolean method property : " + token.getValue(), e);
  188.         }

  189.         // フィールドアクセス
  190.         final String fieldName = token.getValue();
  191.         try {
  192.             Field field = allowPrivate ?
  193.                     targetClass.getDeclaredField(fieldName) : targetClass.getField(fieldName);
  194.             field.setAccessible(true);

  195.             return field.get(targetObj);

  196.         } catch (NoSuchFieldException | SecurityException e) {
  197.             // not found field

  198.         } catch (IllegalArgumentException | IllegalAccessException e) {
  199.             // 値の取得に失敗
  200.             throw new PropertyAccessException("fail access field property : " + token.getValue(), e);
  201.         }

  202.         throw new PropertyAccessException("not found property : " + token.getValue());

  203.     }

  204.     private Object accessPropertyByKey(final Object targetObj, final Token.Key token) {

  205.         if(targetObj == null) {
  206.             if(ignoreNull) {
  207.                 return null;
  208.             } else {
  209.                 throw new NullPointerException("access object is null. property key = " + token.getValue());
  210.             }

  211.         }

  212.         final Class<?> targetClass = targetObj.getClass();

  213.         if(Collection.class.isAssignableFrom(targetClass)) {
  214.             final int index;
  215.             try {
  216.                 index = Integer.parseInt(token.getKey().trim());
  217.             } catch (NumberFormatException e) {
  218.                 throw new PropertyAccessException("wrong key value :" + token.getValue());
  219.             }

  220.             final List<?> list = Utils.convertCollectionToList((Collection<?>) targetObj);
  221.             if((index < 0 || index >= list.size()) && ignoreNotFoundKey) {
  222.                 return null;
  223.             }

  224.             return list.get(index);

  225.         } else if (targetClass.isArray()) {
  226.             final int index;
  227.             try {
  228.                 index = Integer.parseInt(token.getKey().trim());
  229.             } catch (NumberFormatException e) {
  230.                 throw new PropertyAccessException("wrong key value :" + token.getValue());
  231.             }


  232.             final List<?> list = Utils.asList(targetObj, targetClass.getComponentType());
  233.             if((index < 0 || index >= list.size()) && ignoreNotFoundKey) {
  234.                 return null;
  235.             }

  236.             return list.get(index);

  237.         } else if(Map.class.isAssignableFrom(targetClass)) {

  238.             String strKey = token.getKey();
  239.             Map<?, ?> map = (Map<?, ?>) targetObj;
  240.             for(Map.Entry<?, ?> entry : map.entrySet()) {
  241.                 if(entry.getKey().toString().equals(strKey)) {
  242.                     return entry.getValue();
  243.                 }
  244.             }

  245.             // 存在するキーがない場合
  246.             if(ignoreNotFoundKey) {
  247.                 return null;
  248.             }

  249.             throw new IllegalStateException("not found map key : " + strKey);

  250.         }

  251.         throw new PropertyAccessException("not support key access : " + targetClass.getName());

  252.     }

  253.     /**
  254.      * 実行時オプション - 非公開のプロパティにアクセス可能かどうか。
  255.      * @return true: アクセスを許可する。false: デフォルト値。
  256.      */
  257.     public boolean isAllowPrivate() {
  258.         return allowPrivate;
  259.     }

  260.     /**
  261.      * 実行時オプション - 非公開のプロパティにアクセス可能かどうか。
  262.      * @param allowPrivate true: アクセスを許可する。
  263.      */
  264.     public void setAllowPrivate(boolean allowPrivate) {
  265.         this.allowPrivate = allowPrivate;
  266.     }

  267.     /**
  268.      * 実行時オプション - 値がnullの場合に例外をスローしないでその時点で処理を終了するかどうか。
  269.      * @return true: その時点で処理を終了する。false: デフォルト値。
  270.      */
  271.     public boolean isIgnoreNull() {
  272.         return ignoreNull;
  273.     }

  274.     /**
  275.      * 実行時オプション - 値がnullの場合に例外をスローしないでその時点で処理を終了するかどうか。
  276.      * @param ignoreNull true: その時点で処理を終了する。
  277.      */
  278.     public void setIgnoreNull(boolean ignoreNull) {
  279.         this.ignoreNull = ignoreNull;
  280.     }

  281.     /**
  282.      * 実行時オプション - 配列/Collection/Mapにアクセスする際に指定したキーの要素が存在しない場合に処理を終了するかどうか。
  283.      * @return true:その時点で処理を終了する。false: デフォルト値。
  284.      */
  285.     public boolean isIgnoreNotFoundKey() {
  286.         return ignoreNotFoundKey;
  287.     }

  288.     /**
  289.      * 実行時オプション - 配列/Collection/Mapにアクセスする際に指定したキーの要素が存在しない場合に処理を終了するかどうか。
  290.      * @param ignoreNotFoundKey true:その時点で処理を終了する。
  291.      */
  292.     public void setIgnoreNotFoundKey(boolean ignoreNotFoundKey) {
  293.         this.ignoreNotFoundKey = ignoreNotFoundKey;
  294.     }

  295.     /**
  296.      * プロパティの解析結果をキャッシュするかどうか。
  297.      * @return true: キャッシュする。false: デフォルト値。
  298.      */
  299.     public boolean isCacheWithPath() {
  300.         return cacheWithPath;
  301.     }

  302.     /**
  303.      * プロパティの解析結果をキャッシュするかどうか。
  304.      * @param cacheWithPath true: キャッシュする。
  305.      */
  306.     public void setCacheWithPath(boolean cacheWithPath) {
  307.         this.cacheWithPath = cacheWithPath;
  308.     }

  309. }