package shaman.hive.udf;

import java.util.Map;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

@Description(value="_FUNC_ sum values of a map", 
        name="shaman_sum_mapvalue")
public class UDFMapValueSum extends GenericUDF {

    private MapObjectInspector inputOI;
    
    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        if (arguments.length != 1) {
            throw new UDFArgumentLengthException("_FUNC_ take one arguments, map");
        }
        this.inputOI = (MapObjectInspector) arguments[0];
        return PrimitiveObjectInspectorFactory.javaLongObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        long result = 0;
        @SuppressWarnings("unchecked")
        Map<String, Long> map = (Map<String, Long>) inputOI.getMap(arguments[0].get());
        for (Long l : map.values()) {
            result += l;
        }
        return result;
    }

    @Override
    public String getDisplayString(String[] children) {
        return "Sum the value of map value";
    }

}

@@ -468,32 +468,111 @@
 bjectInspector;%0A
+import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;%0A
 import org.apach
@@ -651,16 +651,16 @@
 actory;%0A
-
 %0A@Descri
@@ -828,16 +828,53 @@
 nputOI;%0A
+    private ObjectInspector valueOI;%0A
     %0A   
@@ -1170,16 +1170,72 @@
 nts%5B0%5D;%0A
+        valueOI = inputOI.getMapValueObjectInspector();%0A
         
@@ -1389,32 +1389,41 @@
 HiveException %7B%0A
+        %0A
         long res
@@ -1429,16 +1429,17 @@
 sult = 0
+l
 ;%0A      
@@ -1444,90 +1444,23 @@
     
-@SuppressWarnings(%22unchecked%22)%0A        Map%3CString, Long%3E map = (Map%3CString, Long%3E)
+Map%3C?, ?%3E map =
  inp
@@ -1505,20 +1505,22 @@
    for (
-Long
+Object
  l : map
@@ -1548,19 +1548,307 @@
     
-result += l
+valueOI.getCategory();%0A            PrimitiveObjectInspector oi = PrimitiveObjectInspectorFactory.getPrimitiveObjectInspectorFromClass(valueOI.getClass());%0A            System.out.println(oi);%0A            System.out.println(valueOI.getCategory());%0A            System.out.println(valueOI.getTypeName())
 ;%0A  

add debug info