/** Returns what is actually inserted into the answer */ static SelfDescribingObject insertedObject(Object obj, String structType) { Schema targetSchema = NamedStructureSpecifier.JAVA_MAP.get(structType).getSchema(); return new SelfDescribingObject( targetSchema, PropertySpecifier.convertTypeIfNeeded(obj, targetSchema)); } }
/** * Uses {@code propertyDescriptor} to extract the property value from {@code object} and insert * into {@code row} at {@code columnName}. * * @throws ClassCastException if the recovered property value is not compatible with the specified * {@link Schema} in the {@code propertyDescriptor}. */ public static <T> void fillProperty( PropertyDescriptor<T> propertyDescriptor, T object, String columnName, RowBuilder row) { checkArgument(propertyDescriptor != null, "'propertyDescriptor' cannot be null"); checkArgument(object != null, "'object' cannot be null"); checkArgument(columnName != null, "'columnName' cannot be null"); checkArgument(row != null, "'row' cannot be null"); Object propertyValue = propertyDescriptor.getGetter().apply(object); propertyValue = PropertySpecifier.convertTypeIfNeeded(propertyValue, propertyDescriptor.getSchema()); fillProperty(columnName, propertyValue, row, propertyDescriptor); // separate for testing }
/** Null should remain null and not crash */ @Test public void convertTypeIfNeededNullInput() { Object propertyValueNull = PropertySpecifier.convertTypeIfNeeded(null, Schema.STRING); assertThat(propertyValueNull, equalTo(null)); }
/** Non-string objects should be mapped to their string forms when the schema is String */ @Test public void convertTypeIfNeededNonStringToString() { Object propertyValueObject = PropertySpecifier.convertTypeIfNeeded( new Configuration("cname", ConfigurationFormat.CISCO_IOS), Schema.STRING); assertThat(propertyValueObject, equalTo("cname")); }
/** Map should be converted to set of strings when the schema is string list */ @Test public void convertTypeIfNeededMapToStringSet() { Object propertyValueMap = PropertySpecifier.convertTypeIfNeeded( ImmutableSortedMap.of("k1", "v1", "k2", "v2"), Schema.list(Schema.STRING)); assertThat(propertyValueMap, equalTo(ImmutableSet.of("k1", "k2"))); }
/** Collection of non-strings should be converted to collection of strings when desired */ @Test public void convertTypeIfNeededNonStringCollectionToStringCollection() { Object propertyValueCollection = PropertySpecifier.convertTypeIfNeeded( ImmutableList.of(new Configuration("cname", ConfigurationFormat.CISCO_IOS)), Schema.list(Schema.STRING)); assertThat(propertyValueCollection, equalTo(ImmutableList.of("cname"))); }
/** Protect other objects for which conversion is not needed */ @Test public void convertTypeIfNeededNoConversion() { Object propertyValueOther = PropertySpecifier.convertTypeIfNeeded(new Node("node"), Schema.NODE); assertThat(propertyValueOther, equalTo(new Node("node"))); }