Force a data object to a Boolean, if possible. Any numeric type can be forced to a Boolean, as well as CharArray, ByteArray. Complex types cannot be forced to a Boolean. This isn't particularly efficient, so if you already know that the object you have is a Boolean you should just cast it. @
(Object o, byte type)
| 647 | * if the type can't be forced to a Boolean. |
| 648 | */ |
| 649 | public static Boolean toBoolean(Object o, byte type) throws ExecException { |
| 650 | try { |
| 651 | switch (type) { |
| 652 | case NULL: |
| 653 | return null; |
| 654 | case BOOLEAN: |
| 655 | return (Boolean) o; |
| 656 | case BYTE: |
| 657 | return Boolean.valueOf(((Byte) o).byteValue() != 0); |
| 658 | case INTEGER: |
| 659 | return Boolean.valueOf(((Integer) o).intValue() != 0); |
| 660 | case LONG: |
| 661 | return Boolean.valueOf(((Long) o).longValue() != 0L); |
| 662 | case BIGINTEGER: |
| 663 | return Boolean.valueOf(!BigInteger.ZERO.equals(((BigInteger) o))); |
| 664 | case BIGDECIMAL: |
| 665 | return Boolean.valueOf(!BigDecimal.ZERO.equals(((BigDecimal) o))); |
| 666 | case FLOAT: |
| 667 | return Boolean.valueOf(((Float) o).floatValue() != 0.0F); |
| 668 | case DOUBLE: |
| 669 | return Boolean.valueOf(((Double) o).doubleValue() != 0.0D); |
| 670 | case BYTEARRAY: |
| 671 | String str = ((DataByteArray) o).toString(); |
| 672 | if (str.equalsIgnoreCase("true")) { |
| 673 | return Boolean.TRUE; |
| 674 | } else if (str.equalsIgnoreCase("false")) { |
| 675 | return Boolean.FALSE; |
| 676 | } else { |
| 677 | return null; |
| 678 | } |
| 679 | case CHARARRAY: |
| 680 | if (((String) o).equalsIgnoreCase("true")) { |
| 681 | return Boolean.TRUE; |
| 682 | } else if (((String) o).equalsIgnoreCase("false")) { |
| 683 | return Boolean.FALSE; |
| 684 | } else { |
| 685 | return null; |
| 686 | } |
| 687 | case DATETIME: |
| 688 | case MAP: |
| 689 | case INTERNALMAP: |
| 690 | case TUPLE: |
| 691 | case BAG: |
| 692 | case UNKNOWN: |
| 693 | default: |
| 694 | int errCode = 1071; |
| 695 | String msg = "Cannot convert a " + findTypeName(o) + " to a Boolean"; |
| 696 | throw new ExecException(msg, errCode, PigException.INPUT); |
| 697 | } |
| 698 | } catch (ClassCastException cce) { |
| 699 | throw cce; |
| 700 | } catch (ExecException ee) { |
| 701 | throw ee; |
| 702 | } catch (NumberFormatException nfe) { |
| 703 | int errCode = 1074; |
| 704 | String msg = "Problem with formatting. Could not convert " + o + " to Float."; |
| 705 | throw new ExecException(msg, errCode, PigException.INPUT, nfe); |
| 706 | } catch (Exception e) { |