BaseCellConverter.java

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

  2. import java.util.Collection;
  3. import java.util.Map;
  4. import java.util.Optional;

  5. import org.apache.poi.ss.usermodel.Cell;
  6. import org.apache.poi.ss.usermodel.CellType;
  7. import org.apache.poi.ss.usermodel.CreationHelper;
  8. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  9. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  10. import org.apache.poi.ss.usermodel.Sheet;
  11. import org.apache.poi.ss.usermodel.VerticalAlignment;
  12. import org.apache.poi.ss.usermodel.Workbook;

  13. import com.gh.mygreen.xlsmapper.Configuration;
  14. import com.gh.mygreen.xlsmapper.XlsMapperException;
  15. import com.gh.mygreen.xlsmapper.fieldaccessor.FieldAccessor;
  16. import com.gh.mygreen.xlsmapper.fieldprocessor.ProcessCase;
  17. import com.gh.mygreen.xlsmapper.localization.MessageBuilder;
  18. import com.gh.mygreen.xlsmapper.textformatter.TextFormatter;
  19. import com.gh.mygreen.xlsmapper.textformatter.TextParseException;
  20. import com.gh.mygreen.xlsmapper.util.CellPosition;
  21. import com.gh.mygreen.xlsmapper.util.POIUtils;
  22. import com.gh.mygreen.xlsmapper.util.Utils;
  23. import com.gh.mygreen.xlsmapper.validation.fieldvalidation.FieldFormatter;

  24. /**
  25.  * {@link CellConverter}を実装するときのベースとなる抽象クラス。
  26.  * 通常は、このクラスを継承して{@link CellConverter}を実装します。
  27.  *
  28.  * @version 2.0
  29.  * @author T.TSUCHIE
  30.  *
  31.  */
  32. public abstract class BaseCellConverter<T> implements CellConverter<T>, FieldFormatter<T> {

  33.     /**
  34.      * フィールド情報
  35.      */
  36.     protected final FieldAccessor field;

  37.     /**
  38.      * システム設定
  39.      */
  40.     protected final Configuration configuration;

  41.     /**
  42.      * 値をトリムするかどうか
  43.      */
  44.     protected boolean trimmed;

  45.     /**
  46.      * 初期値 - 初期値を持たない場合は空
  47.      */
  48.     protected OptionalProcessCase<T> defaultValue = OptionalProcessCase.empty();

  49.     /**
  50.      * セルの設定 - セルを縮小して表示するかどうか
  51.      */
  52.     protected boolean shrinktToFit;

  53.     /**
  54.      * セルの設定 - 折り返して全体を表示するかどうか
  55.      */
  56.     protected boolean wrapText;

  57.     /**
  58.      * セルの設定 - インデント
  59.      */
  60.     protected short indent;

  61.     /**
  62.      * セルの設定 - 横位置
  63.      */
  64.     protected Optional<HorizontalAlignment> horizontalAlignment = Optional.empty();

  65.     /**
  66.      * セルの設定 - 縦位置
  67.      */
  68.     protected Optional<VerticalAlignment> verticalAlignment = Optional.empty();

  69.     /**
  70.      * 書き込み時の数式を設定する
  71.      */
  72.     protected Optional<CellFormulaHandler> formulaHandler = Optional.empty();

  73.     /**
  74.      * 文字列とオブジェクトを相互変換するフォーマッタ
  75.      */
  76.     protected TextFormatter<T> textFormatter;

  77.     public BaseCellConverter(final FieldAccessor field, final Configuration config) {
  78.         this.field = field;
  79.         this.configuration = config;
  80.     }

  81.     @Override
  82.     public T toObject(final Cell cell) throws XlsMapperException {

  83.         final ProcessCase processCase = ProcessCase.Load;
  84.         final String formattedValue = Utils.trim(configuration.getCellFormatter().format(cell), trimmed);

  85.         // デフォルト値の設定
  86.         if(isEmptyCell(formattedValue, cell) && defaultValue.isPresent(processCase)) {
  87.             return defaultValue.get(processCase);
  88.         }

  89.         // 数式のセルの場合、予め評価しておく
  90.         final Cell evaluatedCell;
  91.         if(cell.getCellType().equals(CellType.FORMULA)) {
  92.             final Workbook workbook = cell.getSheet().getWorkbook();
  93.             final CreationHelper helper = workbook.getCreationHelper();
  94.             final FormulaEvaluator evaluator = helper.createFormulaEvaluator();

  95.             evaluatedCell = evaluator.evaluateInCell(cell);
  96.         } else {
  97.             evaluatedCell = cell;
  98.         }

  99.         return parseCell(evaluatedCell, formattedValue);
  100.     }

  101.     /**
  102.      * セルをJavaのオブジェクト型に変換します。
  103.      * @param evaluatedCell 数式を評価済みのセル
  104.      * @param formattedValue フォーマット済みのセルの値。トリミングなど適用済み。
  105.      * @return 変換した値を返す。
  106.      * @throws TypeBindException 変換に失敗した場合
  107.      */
  108.     protected abstract T parseCell(Cell evaluatedCell, String formattedValue) throws TypeBindException;

  109.     /**
  110.      * セルの値をパースしJavaオブジェクトに型変換するとこに失敗したときの例外{@link TypeBindException}を作成します。
  111.      * @since 2.0
  112.      * @param error 例外情報
  113.      * @param cell パースに失敗したセル
  114.      * @param cellValue パースに失敗した値
  115.      * @return マッピングに失敗したときの例外のインスタンス
  116.      */
  117.     public TypeBindException newTypeBindExceptionOnParse(final Exception error,  final Cell cell, final Object cellValue) {

  118.         final String message = MessageBuilder.create("cell.typeBind.failParse")
  119.                 .var("property", field.getNameWithClass())
  120.                 .var("cellAddress", POIUtils.formatCellAddress(cell))
  121.                 .var("cellValue", cellValue.toString())
  122.                 .varWithClass("type", field.getType())
  123.                 .format();

  124.         final TypeBindException bindException = new TypeBindException(error, message, field.getType(), cellValue);
  125.         if(error instanceof TextParseException) {
  126.             bindException.addAllMessageVars(((TextParseException)error).getErrorVariables());
  127.         }

  128.         return bindException;

  129.     }

  130.     /**
  131.      * セルの値をパースしセルの値をJavaオブジェクトに型変換するとに失敗したときの例外{@link TypeBindException}を作成します。
  132.      * @since 2.0
  133.      * @param cell パースに失敗したセル
  134.      * @param cellValue パースに失敗した値
  135.      * @return マッピングに失敗したときの例外のインスタンス
  136.      */
  137.     public TypeBindException newTypeBindExceptionOnParse(final Cell cell, final Object cellValue) {

  138.         final String message = MessageBuilder.create("cell.typeBind.failParse")
  139.                 .var("property", field.getNameWithClass())
  140.                 .var("cellAddress", POIUtils.formatCellAddress(cell))
  141.                 .var("cellValue", cellValue.toString())
  142.                 .varWithClass("type", field.getType())
  143.                 .format();

  144.         final TypeBindException bindException = new TypeBindException(message, field.getType(), cellValue);

  145.         return bindException;

  146.     }

  147.     /**
  148.      * セルの値が空かどうか判定します。
  149.      * <p>読み込み時のセルの値をJavaオブジェクトにマッピングする際に呼ばれます。</p>
  150.      * <p>
  151.      *   通常は、{@code formattedValue.isEmpty()} で判定しますが、
  152.      *   ハイパーリンクのようにマッピング対象の値がセルの値だけではない場合は、
  153.      *   オーバライドして判定方法を変更します。
  154.      * </p>
  155.      *
  156.      * @param formattedValue フォーマットしたセルの値
  157.      * @param cell 評価対象のセル
  158.      * @return trueの場合、空と判定する。
  159.      */
  160.     protected boolean isEmptyCell(final String formattedValue, final Cell cell) {
  161.         return formattedValue.isEmpty();
  162.     }

  163.     @Override
  164.     public Cell toCell(final T targetValue, final Object targetBean, final Sheet sheet, final CellPosition address) throws XlsMapperException {

  165.         final ProcessCase processCase = ProcessCase.Save;
  166.         final Cell cell = POIUtils.getCell(sheet, address);

  167.         final CellStyleProxy cellStyle = new CellStyleProxy(cell);

  168.         // セルの制御の設定
  169.         if(shrinktToFit) {
  170.             cellStyle.setShrinkToFit();

  171.         } else if(wrapText) {
  172.             cellStyle.setWrapText();
  173.         }

  174.         // 横位置
  175.         horizontalAlignment.ifPresent(align -> cellStyle.setHorizontalAlignment(align));

  176.         // インデント
  177.         if(indent >= 0) {
  178.             cellStyle.setIndent(indent);
  179.         }

  180.         // 縦位置
  181.         verticalAlignment.ifPresent(align -> cellStyle.setVerticalAlignment(align));

  182.         // デフォルト値の設定
  183.         final T cellValue;
  184.         if(targetValue == null && defaultValue.isPresent(processCase)) {
  185.             cellValue = defaultValue.get(processCase);
  186.         } else {
  187.             cellValue = targetValue;
  188.         }

  189.         // 各書式に沿った値の設定
  190.         setupCell(cell, Optional.ofNullable(cellValue));

  191.         // 数式の設定
  192.         formulaHandler.ifPresent(handler -> {
  193.             if(isEmptyValue(cellValue, configuration) || handler.isPrimaryFormula()) {
  194.                 handler.handleFormula(field, configuration, cell, targetBean);
  195.             }
  196.         });

  197.         return cell;
  198.     }

  199.     /**
  200.      * オブジェクトの値を空と判定する
  201.      * @param obj 判定対象の値
  202.      * @param config システム情報
  203.      * @return trueの場合、空と判定する。
  204.      */
  205.     @SuppressWarnings("rawtypes")
  206.     protected boolean isEmptyValue(final T obj, final Configuration config) {
  207.         if(obj == null) {
  208.             return true;
  209.         }

  210.         if(obj instanceof String) {
  211.             return ((String)obj).isEmpty();
  212.         }

  213.         if(char.class.isAssignableFrom(obj.getClass()) || obj instanceof Character) {
  214.             return ((Character)obj) == '\u0000';
  215.         }

  216.         if(obj.getClass().isArray()) {
  217.             return ((Object[])obj).length == 0;
  218.         }

  219.         if(obj instanceof Collection) {
  220.             return ((Collection)obj).isEmpty();
  221.         }

  222.         if(obj instanceof Map) {
  223.             return ((Map)obj).isEmpty();
  224.         }

  225.         return false;
  226.     }

  227.     /**
  228.      * 書き込み時のセルに値と書式を設定します。
  229.      * @param cell 設定対象のセル
  230.      * @param cellValue 設定対象の値。
  231.      * @throws TypeBindException 変換に失敗した場合
  232.      */
  233.     protected abstract void setupCell(Cell cell, Optional<T> cellValue) throws TypeBindException;

  234.     /**
  235.      * フィールド情報を取得します。
  236.      * @return フィールド情報
  237.      */
  238.     public FieldAccessor getField() {
  239.         return field;
  240.     }

  241.     /**
  242.      * システム情報を取得します。
  243.      * @return システム情報
  244.      */
  245.     public Configuration getConfiguration() {
  246.         return configuration;
  247.     }

  248.     @Override
  249.     public String format(T value) {
  250.         return textFormatter.format(value);
  251.     }

  252.     /**
  253.      * 値をトリミングするかどうか設定する
  254.      * @param trimmed trueの場合、トリムする。
  255.      */
  256.     public void setTrimmed(boolean trimmed) {
  257.         this.trimmed = trimmed;
  258.     }

  259.     /**
  260.      * 値をトリミングするかどうか。
  261.      * @return trueの場合、トリムする。
  262.      */
  263.     public boolean isTrimmed() {
  264.         return trimmed;
  265.     }

  266.     /**
  267.      * 初期値を設定します。
  268.      * @param defaultValue 初期値となるオブジェクト。
  269.      * @param cases 該当する処理ケース
  270.      */
  271.     public void setDefaultValue(T defaultValue, ProcessCase[] cases) {
  272.         this.defaultValue = OptionalProcessCase.of(defaultValue, cases);
  273.     }

  274.     /**
  275.      * 初期値を取得します。
  276.      * @return 設定されていない場合、空を返します。
  277.      */
  278.     public OptionalProcessCase<T> getDefaultValue() {
  279.         return defaultValue;
  280.     }

  281.     /**
  282.      * セルの設定 - セルを縮小して表示するかどうか設定します。
  283.      * @param shrinktToFit trueの場合、セルを縮小して表示します。
  284.      */
  285.     public void setShrinktToFit(boolean shrinktToFit) {
  286.         this.shrinktToFit = shrinktToFit;
  287.     }

  288.     /**
  289.      * セルの設定 - セルを縮小して表示するかどうか。
  290.      * @return trueの場合、セルを縮小して表示します。
  291.      */
  292.     public boolean isShrinktToFit() {
  293.         return shrinktToFit;
  294.     }

  295.     /**
  296.      * セルの設定 - 折り返して全体を表示するかどうか設定します。
  297.      * @param wrapText trueの場合、折り返して全体を表示します。
  298.      */
  299.     public void setWrapText(boolean wrapText) {
  300.         this.wrapText = wrapText;
  301.     }

  302.     /**
  303.      * セルの設定 - 折り返して全体を表示するかどうか。
  304.      * @return trueの場合、折り返して全体を表示します。
  305.      */
  306.     public boolean isWrapText() {
  307.         return wrapText;
  308.     }

  309.     /**
  310.      * セルの設定 - インデント
  311.      * @return 0以上の場合、有効。
  312.      */
  313.     public short getIndent() {
  314.         return indent;
  315.     }

  316.     /**
  317.      * セルの設定 - インデント
  318.      * @param indent 0以上の場合、有効。
  319.      */
  320.     public void setIndent(short indent) {
  321.         this.indent = indent;
  322.     }

  323.     /**
  324.      * セルの設定 - 横位置
  325.      * @return 横位置。設定がない場合は空を返す。
  326.      */
  327.     public Optional<HorizontalAlignment> getHorizontalAlignment() {
  328.         return horizontalAlignment;
  329.     }

  330.     /**
  331.      * セルの設定 - 横位置
  332.      * @param horizontalAlignment 横位置
  333.      */
  334.     public void setHorizontalAlignment(HorizontalAlignment horizontalAlignment) {
  335.         this.horizontalAlignment = Optional.ofNullable(horizontalAlignment);
  336.     }

  337.     /**
  338.      *  セルの設定 - 縦位置
  339.      * @return 縦位置。設定がない場合は空を返す。
  340.      */
  341.     public Optional<VerticalAlignment> getVerticalAlignment() {
  342.         return verticalAlignment;
  343.     }

  344.     /**
  345.      * セルの設定 - 縦位置
  346.      * @param verticalAlignment 縦位置
  347.      */
  348.     public void setVerticalAlignment(VerticalAlignment verticalAlignment) {
  349.         this.verticalAlignment = Optional.ofNullable(verticalAlignment);
  350.     }

  351.     /**
  352.      * 数式を処理するハンドラを設定する
  353.      * @param formulaHandler 数式を処理するハンドラを
  354.      */
  355.     public void setFormulaHandler(CellFormulaHandler formulaHandler) {
  356.         this.formulaHandler = Optional.of(formulaHandler);
  357.     }

  358.     /**
  359.      * 文字列とオブジェクトを相互変換するフォーマッタを取得します。
  360.      * @param textFormatter フォーマッタ
  361.      */
  362.     public void setTextFormatter(TextFormatter<T> textFormatter) {
  363.         this.textFormatter = textFormatter;
  364.     }

  365.     /**
  366.      * 文字列とオブジェクトを相互変換するフォーマッタを取得します。
  367.      * @return フォーマッタ
  368.      */
  369.     public TextFormatter<T> getTextFormatter() {
  370.         return textFormatter;
  371.     }

  372. }