Force a data object to an Integer, if possible. Any numeric type can be forced to an Integer (though precision may be lost), as well as CharArray, ByteArray, or Boolean. Complex types cannot be forced to an Integer. This isn't particularly efficient, so if you already know that the object
(Object o,byte type)
| 727 | * @throws ExecException if the type can't be forced to an Integer. |
| 728 | */ |
| 729 | public static Integer toInteger(Object o,byte type) throws ExecException { |
| 730 | try { |
| 731 | switch (type) { |
| 732 | case BOOLEAN: |
| 733 | if (((Boolean)o) == true) { |
| 734 | return Integer.valueOf(1); |
| 735 | } else { |
| 736 | return Integer.valueOf(0); |
| 737 | } |
| 738 | |
| 739 | case BYTE: |
| 740 | return Integer.valueOf(((Byte)o).intValue()); |
| 741 | |
| 742 | case INTEGER: |
| 743 | return (Integer)o; |
| 744 | |
| 745 | case LONG: |
| 746 | return Integer.valueOf(((Long)o).intValue()); |
| 747 | |
| 748 | case FLOAT: |
| 749 | return Integer.valueOf(((Float)o).intValue()); |
| 750 | |
| 751 | case DOUBLE: |
| 752 | return Integer.valueOf(((Double)o).intValue()); |
| 753 | |
| 754 | case BYTEARRAY: |
| 755 | return Integer.valueOf(((DataByteArray)o).toString()); |
| 756 | |
| 757 | case CHARARRAY: |
| 758 | return Integer.valueOf((String)o); |
| 759 | |
| 760 | case BIGINTEGER: |
| 761 | return Integer.valueOf(((BigInteger)o).intValue()); |
| 762 | |
| 763 | case BIGDECIMAL: |
| 764 | return Integer.valueOf(((BigDecimal)o).intValue()); |
| 765 | |
| 766 | case NULL: |
| 767 | return null; |
| 768 | |
| 769 | case DATETIME: |
| 770 | return Integer.valueOf(Long.valueOf(((DateTime)o).getMillis()).intValue()); |
| 771 | |
| 772 | case MAP: |
| 773 | case INTERNALMAP: |
| 774 | case TUPLE: |
| 775 | case BAG: |
| 776 | case UNKNOWN: |
| 777 | default: |
| 778 | int errCode = 1071; |
| 779 | String msg = "Cannot convert a " + findTypeName(o) + |
| 780 | " to an Integer"; |
| 781 | throw new ExecException(msg, errCode, PigException.INPUT); |
| 782 | } |
| 783 | } catch (ClassCastException cce) { |
| 784 | throw cce; |
| 785 | } catch (ExecException ee) { |
| 786 | throw ee; |