TNodeIf extends TNode { @VisibleForTesting static String isTruthy(Object val) { if (val == null) { return "null"; } if (val instanceof String) { String sVal = (String) val; return sVal.isEmpty() ? "empty" : null; } else if (val instanceof Iterable) { Iterable itVal = (Iterable) val; return itVal.iterator().hasNext() ? null : "empty"; } else if (val instanceof Enumeration) { Enumeration itVal = (Enumeration) val; return itVal.hasMoreElements() ? null : "empty"; } else if (val instanceof Iterator) { Iterator itVal = (Iterator) val; return itVal.hasNext() ? null : "empty"; } else if (val instanceof Map) { Map mapVal = (Map) val; return mapVal.isEmpty() ? "empty" : null; } else if (val instanceof Boolean) { return (Boolean) val ? null : "false"; } else if (val instanceof Double) { return Math.abs((Double) val) > PRECISION ? null : "0"; } else if (val instanceof Float) { return Math.abs((Float) val) > PRECISION ? null : "0"; } else if (val instanceof Number) { return ((Number) val).intValue() != 0 ? null : "0"; } else if (val instanceof Character) { return null; } else if (val.getClass().isArray()) { return ((Object[]) val).length > 0 ? null : "empty"; } else { throw new AssertionError("Not a recognized type: " + val.getClass() + ": " + val); } } TNodeIf(SystemInfo info, TextContentParser parser, String qName, Attributes attributes, String expr, boolean onlyChildren); @Override void render(TRenderContext context); static final double PRECISION; }
@Test public void testIsTruthy() throws Exception { assertNull(TNodeIf.isTruthy("1")); assertNull(TNodeIf.isTruthy("hi")); assertNull(TNodeIf.isTruthy(true)); assertNull(TNodeIf.isTruthy(1.0)); assertNull(TNodeIf.isTruthy(0.5f)); assertNull(TNodeIf.isTruthy(0.5)); assertNull(TNodeIf.isTruthy(1)); assertNull(TNodeIf.isTruthy(new String[]{"1"})); assertNull(TNodeIf.isTruthy(Lists.newArrayList(2))); assertNull(TNodeIf.isTruthy(Lists.newArrayList(2))); assertNull(TNodeIf.isTruthy(Lists.newArrayList(2).iterator())); assertNull(TNodeIf.isTruthy(Collections.singletonMap("key", 2))); assertNotNull(TNodeIf.isTruthy(Collections.emptyMap())); assertNotNull(TNodeIf.isTruthy(Collections.emptyEnumeration())); assertNotNull(TNodeIf.isTruthy(Collections.emptyList())); assertNotNull(TNodeIf.isTruthy(Collections.emptyList().iterator())); assertNotNull(TNodeIf.isTruthy(0)); assertNotNull(TNodeIf.isTruthy(0.000000000000000001)); assertNotNull(TNodeIf.isTruthy(0.000000000000000001f)); assertNotNull(TNodeIf.isTruthy(false)); assertNotNull(TNodeIf.isTruthy("")); assertNotNull(TNodeIf.isTruthy(null)); }