DatatypeTransformer { public static <T> T transform(Object value, Class<T> targetType) { if (value == null) { return null; } if (targetType.equals(String.class)) { return targetType.cast(value instanceof LangString ? ((LangString) value).getValue() : value.toString()); } final Class<?> sourceType = value.getClass(); if (targetType.isAssignableFrom(sourceType)) { return targetType.cast(value); } final Pair p = new Pair(sourceType, targetType); if (TRANSFORMERS.containsKey(p)) { return targetType.cast(TRANSFORMERS.get(p).apply(value)); } final Optional<T> result = tryConversionUsingConstructor(value, targetType); return result.orElseThrow(() -> new UnsupportedTypeTransformation( String.format("Cannot transform value %s of type %s to target type %s.", value, value.getClass(), targetType))); } private  DatatypeTransformer(); static T transform(Object value, Class<T> targetType);  }
@Test void transformReturnsNullForNullInput() { assertNull(DatatypeTransformer.transform(null, String.class)); }
@Test void transformConvertsValueToTargetType() { final Integer value = 117; final Double result = DatatypeTransformer.transform(value, Double.class); assertEquals(value.doubleValue(), result, 0.01); }
@Test void transformThrowsUnsupportedTypeConversionWhenNoTransformerIsFound() { final Integer value = 117; final UnsupportedTypeTransformation ex = assertThrows(UnsupportedTypeTransformation.class, () -> DatatypeTransformer.transform(value, URL.class)); assertEquals(String.format("Cannot transform value %s of type %s to target type %s.", value, Integer.class, URL.class), ex.getMessage()); }
@Test void transformToStringDoesNotRequireExplicitTransformer() { final Integer value = 117; final String result = DatatypeTransformer.transform(value, String.class); assertEquals(value.toString(), result); }
@Test void transformCastsValueWithoutTransformerWhenValueIsAssignableToTargetType() { final Integer value = 117; final Number result = DatatypeTransformer.transform(value, Number.class); assertSame(result, value); }
@Test void transformSupportsConversionUsingConstructorWithParameterMatchingTransformedValueType() { final String value = "http: final URL result = DatatypeTransformer.transform(value, URL.class); assertEquals(value, result.toString()); }
@Test void transformThrowsUnsupportedTypeConversionWhenTargetTypeDoesNotHaveMatchingConstructor() { final String value = "http: final UnsupportedTypeTransformation ex = assertThrows(UnsupportedTypeTransformation.class, () -> DatatypeTransformer.transform(value, OWLClassA.class)); assertEquals(String.format("Cannot transform value %s of type %s to target type %s.", value, String.class, OWLClassA.class), ex.getMessage()); }
@Test void transformTransformsLangStringToString() { final LangString value = new LangString("test", "en"); final String result = DatatypeTransformer.transform(value, String.class); assertEquals(value.getValue(), result); }