All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jxls.functions.GroupSum Maven / Gradle / Ivy

The newest version!
package org.jxls.functions;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;

/**
 * 

Group sum

*

The sum function for calculation a group sum takes two arguments: the collection as JEXL expression (or its name as a String) * and the name (as String) of the attribute. The attribute can be a object property or a Map entry. The value type T can be of any * type and is implemented by a generic SummarizerBuilder.

* *

Example

*

Add an instance of this class e.g. with name "G" to your Context.

*
${G.sum("salary", employees.items)}
*

Above the 2nd argument is a JEXL expression. The collection name as String is also possible:

*
${G.sum("salary", "employees.items")}
*/ public class GroupSum { private final Context context; private final SummarizerBuilder sumBuilder; public GroupSum(Context context, SummarizerBuilder sumBuilder) { this.context = context; this.sumBuilder = sumBuilder; } /** * Returns the sum of the given field of all items. * * @param fieldName name of the field of type T to be summed (without the loop var name!) * @param expression JEXL expression as String, usually name of the Collection, often ends with ".items" * @return sum of type T */ public T sum(String fieldName, String expression) { return sum(fieldName, getItems(expression)); } /** * Returns the sum of the given field of all items. * * @param fieldName name of the field of type T to be summed (without the loop var name!) * @param collection the collection; inside Excel file it's a JEXL expression * @return sum of type T */ public T sum(String fieldName, Collection collection) { Summarizer sum = sumBuilder.build(); for (Object i : collection) { sum.add(getValue(i, fieldName)); } return sum.getSum(); } private Object getValue(Object i, String fieldName) { if (i instanceof Map) { Map map = (Map) i; if (!map.containsKey(fieldName)) { throw new RuntimeException("Attribute " + fieldName + " does not exist in collection element!"); } return map.get(fieldName); } else { try { return PropertyUtils.getProperty(i, fieldName); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } } } @SuppressWarnings("unchecked") private Collection getItems(String expression) { Object result = getValue(expression); if (result == null) { throw new NullPointerException("\"" + expression + "\" is null!"); } else if (!(result instanceof Collection)) { throw new ClassCastException(expression + " is not a Collection!"); } return (Collection) result; } private Object getValue(String expression) { return new JexlExpressionEvaluator(expression).evaluate(context.toMap()); } }