private <X> TypedValue<X> convertToType(final XQueryContext xqueryContext, final String argumentName, final TypedValue typedValue, final org.exquery.xquery.Type destinationType, final Class<X> underlyingDestinationClass) throws RestXqServiceException {
//TODO consider changing Types that can be used as <T> to TypedValue to a set of interfaces for XDM types that
//require absolute minimal implementation, and we provide some default or abstract implementations if possible
final Item convertedValue;
try {
final int existDestinationType = TypeAdapter.toExistType(destinationType);
final Item value;
//TODO This type system is a complete mess:
//EXQuery XDM should not have any concrete types, just interfaces
//some of the abstract code in EXQuery needs to be able to instantiate types.
//Consider a factory or java.util.ServiceLoader pattern
if(typedValue instanceof org.exquery.xdm.type.StringTypedValue) {
value = new StringValue(((org.exquery.xdm.type.StringTypedValue)typedValue).getValue());
} else if(typedValue instanceof org.exquery.xdm.type.Base64BinaryTypedValue) {
value = BinaryValueFromInputStream.getInstance(xqueryContext, new Base64BinaryValueType(), ((org.exquery.xdm.type.Base64BinaryTypedValue)typedValue).getValue());
} else {
value = (Item)typedValue.getValue();
}
if(existDestinationType == value.getType()) {
convertedValue = value;
} else if(value instanceof AtomicValue) {
convertedValue = value.convertTo(existDestinationType);
} else {
LOG.warn("Could not convert parameter '" + argumentName + "' from '" + typedValue.getType().name() + "' to '" + destinationType.name() + "'.");
convertedValue = value;
}