package com.onaro.util.jfc.grouping; /** * Copies a value from a row in the group to the group. If the group contains * different values, than don't copy. */ public class CopySummarizer implements Summarizer { /** * Default value to display in case the values are not the same * Leave null if no value should be set */ private String defaultValue; /** * The column from which the value is copied and to which it is copied. */ private int copyToColumn; /** * alterntive column from which the value is copied */ private int copyFromColumn; /** * Initialize a copier for the given column. * @param column the column to copy from and to put the value in * @param defaultValue Default value to display in case the values are not the same */ public CopySummarizer(int column, String defaultValue) { this(column, column, defaultValue); } /** * Initialize a copier for the given column. * Note that there should be summarizers for the copyFromColumn itself or the value of the nodes in complex grouping will be empty * @param copyToColumn index of the column where the value will be included * @param copyFromColumn index of the column where the value will copied from * @param defaultValue Default value to display in case the values are not the same */ public CopySummarizer(int copyFromColumn, int copyToColumn, String defaultValue) { this.copyFromColumn = copyFromColumn; this.copyToColumn = copyToColumn; this.defaultValue = defaultValue; } /** * Copy the value for the specified column to of the first row to the given * node. However, if the children has different values, don't copy any of them. * @param node the node */ public void updateSummary(Node node) { int childCount = node.getChildCount(); if (childCount > 0) { Object commonValue = getCommonValue(node, childCount); if (commonValue != null) { node.setValueAt(copyToColumn, commonValue); } } } /** * If all the children has the same value return it, or the default value if not. * Note - if the default value is not set, null will be returned */ private Object getCommonValue(Node node, int childCount) { Object valueOfFirstChild = node.getChild(0).getValueAt(copyFromColumn); for (int child = 1 ; child < childCount; ++child) { Object childValue = node.getChild(child).getValueAt(copyFromColumn); if (valueOfFirstChild != childValue) { if (valueOfFirstChild == null || childValue == null) return defaultValue; if (!valueOfFirstChild.equals(childValue)) return defaultValue; } } return valueOfFirstChild; } }