/*
(non-Javadoc)
@see org.springframework.ldap.odm.typeconversion.ConverterManager#convert(java.lang.Object, java.lang.String, java.lang.Class)
484607
@SuppressWarnings("unchecked")
    public <T> T convert(Object source, String syntax, Class<T> toClass) {
        Object result = null;

        // What are we converting form
        Class<?> fromClass = source.getClass();

        // Deal with primitives
        Class<?> targetClass = toClass;
        if (toClass.isPrimitive()) {
            targetClass = primitiveTypeMap.get(toClass);
        }

        // Try to convert with any syntax we have been given
        Converter syntaxConverter = converters.get(makeConverterKey(fromClass, syntax, targetClass));
        if (syntaxConverter != null) {
            try {
                result = syntaxConverter.convert(source, targetClass);
            } catch (Exception e) {
                // Ignore as we may still be able to convert successfully
            }
        }

        // Do we actually need to do any conversion?
        if (result == null && targetClass.isAssignableFrom(fromClass)) {
            result = source;
        }

        // If we were given a syntax and we failed to convert drop back to any mapping
        // that will work from class -> to class
        if (result == null && syntax != null) {
            Converter nullSyntaxConverter = converters.get(makeConverterKey(fromClass, null, targetClass));
            if (nullSyntaxConverter != null) {
                try {
                    result = nullSyntaxConverter.convert(source, targetClass);
                } catch (Exception e) {
                    // Handled at the end of the method
                }
            }
        }

        if (result == null) {
            throw new ConverterException(String.format(
                    "Cannot convert %1$s of class %2$s via syntax %3$s to class %4$s", source, source.getClass(),
                    syntax, toClass));
        }

        // We cannot do the safe thing of doing a .cast as we need to rely on auto-unboxing to deal with primitives!
        return (T)result;
    }
205212
@SuppressWarnings("unchecked")
    public static <T> T convertValue(JsonNode node, Class<T> clazz) {
        if (node instanceof POJONode) {
            return convertValue(DPathUtils.extractValue((POJONode) node), clazz);
        }
        if (clazz == null) {
            throw new NullPointerException("Class parameter is null!");
        }
        if (node == null || node instanceof NullNode || node instanceof MissingNode) {
            return null;
        }
        if (node instanceof POJONode) {
            return convertValue(DPathUtils.extractValue((POJONode) node), clazz);
        }
        if (Number.class.isAssignableFrom(clazz) || byte.class == clazz || short.class == clazz
                || int.class == clazz || long.class == clazz || float.class == clazz
                || double.class == clazz) {
            return convertNumber(node, clazz);
        }
        if (clazz == Boolean.class || clazz == boolean.class) {
            return (T) convertBoolean(node);
        }
        if (clazz == Character.class || clazz == char.class) {
            return (T) convertChar(node);
        }
        if (Date.class.isAssignableFrom(clazz)) {
            return (T) convertDate(node);
        }
        if (Object[].class.isAssignableFrom(clazz) || List.class.isAssignableFrom(clazz)) {
            return (T) convertArrayOrList(node);
        }
        if (clazz.isAssignableFrom(node.getClass())) {
            return (T) node;
        }
        if (clazz == String.class) {
            return (T) (node.isTextual() ? node.asText() : node.toString());
        }
        throw new IllegalArgumentException(
                "Cannot convert an object of type [" + node.getClass() + "] to [" + clazz + "]!");
    }
533012
public <S, T> T convertTo(Class<T> output, Object object) {
		return convertTo(output, object, DefaultBinding.class);
	}
1198386
@Override
	public T convert(ResponseBody value) throws IOException {
		try {
			return (T) binderContext.parse(value.byteStream(), clazz);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			value.close();
		}
	}
475297
public static <T, U> U convert(T source, Class<U> targetClass) {
        return BeanConvertStrategy.convertBean(source, targetClass);
    }
85197
@SuppressWarnings("unchecked")
    public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException {
        TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls);
        if (typeConverter == null) {
            throw new NoSuchTypeConverterException(cls);
        }
        return typeConverter;
    }
690088
public <T> T convert(Type type, Object value) throws ConvertException {
		return convert(type, value, null);
	}
162531
@Nullable
  private static Converter<List<String>, Object> createPrimitiveTypeConverter(final Class<?> resultClass) {
    Object defaultValue = defaultValue(resultClass);

    if (defaultValue == null) {
      // For primitive type, the default value shouldn't be null
      return null;
    }

    return new BasicConverter(defaultValue) {
      @Override
      protected Object convert(String value) throws Exception {
        return valueOf(value, resultClass);
      }
    };
  }
966677
@Override public String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) {
      if (_typeDesc.equals("Z") || _typeDesc.equals("boolean")) {
         return (cvtBooleanToChar);
      } else if (_typeDesc.equals("[Z") || _typeDesc.equals("boolean[]")) {
         return isLocal ? (cvtBooleanArrayToChar) : (cvtBooleanArrayToCharStar);
      } else if (_typeDesc.equals("B") || _typeDesc.equals("byte")) {
         return (cvtByteToChar);
      } else if (_typeDesc.equals("[B") || _typeDesc.equals("byte[]")) {
         return isLocal ? (cvtByteArrayToChar) : (cvtByteArrayToCharStar);
      } else if (_typeDesc.equals("C") || _typeDesc.equals("char")) {
         return (cvtCharToShort);
      } else if (_typeDesc.equals("[C") || _typeDesc.equals("char[]")) {
         return isLocal ? (cvtCharArrayToShort) : (cvtCharArrayToShortStar);
      } else if (_typeDesc.equals("[I") || _typeDesc.equals("int[]")) {
         return isLocal ? (cvtIntArrayToInt) : (cvtIntArrayToIntStar);
      } else if (_typeDesc.equals("[F") || _typeDesc.equals("float[]")) {
         return isLocal ? (cvtFloatArrayToFloat) : (cvtFloatArrayToFloatStar);
      } else if (_typeDesc.equals("[D") || _typeDesc.equals("double[]")) {
         return isLocal ? (cvtDoubleArrayToDouble) : (cvtDoubleArrayToDoubleStar);
      } else if (_typeDesc.equals("[J") || _typeDesc.equals("long[]")) {
         return isLocal ? (cvtLongArrayToLong) : (cvtLongArrayToLongStar);
      } else if (_typeDesc.equals("[S") || _typeDesc.equals("short[]")) {
         return isLocal ? (cvtShortArrayToShort) : (cvtShortArrayToShortStar);
      } else if ("[Ljava/util/concurrent/atomic/AtomicInteger;".equals(_typeDesc) ||
    		  "[Ljava.util.concurrent.atomic.AtomicInteger;".equals(_typeDesc)) {
    	 return (cvtIntArrayToIntStar);
      }
      // if we get this far, we haven't matched anything yet
      if (useClassModel) {
         return (ClassModel.convert(_typeDesc, "", true));
      } else {
         return _typeDesc;
      }
   }
86029
@Override
	public T convert(String name) throws IllegalArgumentException {
		if (name == null) {
			throw new IllegalArgumentException("Cant convert 'null' to " + enumClass.getSimpleName());
		}
		try {
			return Enum.valueOf(enumClass, name);
		} catch (IllegalArgumentException e) {
			// ignore
		}
		try {
			return Enum.valueOf(enumClass, name.toUpperCase());
		} catch (IllegalArgumentException e) {
			// ignore
		}
		try {
			return Enum.valueOf(enumClass, name.toUpperCase().replace("-", "_"));
		} catch (IllegalArgumentException e) {
			// ignore
		}
		throw new IllegalArgumentException("Can't convert " + name + " to " + enumClass.getSimpleName());

	}
509930
private void convertOldIdNameClass() throws RepositoryException {
		String searchRoot = "/jcr:root" + ISO9075.encodePath(StorageConstants.NEXT_SERVER_ROOT);
		String searchPropertyName = "className";
		String searchPropertyValue = "com.asf.nextserver.domain.ParameterValue";
		String statement = searchRoot + "//*[@" + searchPropertyName + "='" + searchPropertyValue + "']";
        QueryResult queryResult = getTemplate().query(statement);

        NodeIterator nodes = queryResult.getNodes();
        LOG.info("Found " + nodes.getSize() +  " parameter value nodes");
        while (nodes.hasNext()) {
        	Node node = nodes.nextNode();
        	Property property = null;
        	try {
        		property = node.getProperty("value");
        	} catch (PathNotFoundException ex) {
        		continue;
        	}
        	try {
	        	Object value = deserialize(property.getBinary().getStream());
	        	if (value instanceof Object[]) {
	        		Object[] values = (Object[]) value;
	        		Object[] convertedValues = new Object[values.length];
		        	boolean converted = false;
	        		for (int i = 0; i < values.length; i++) {
	        			Object tmp = values[i];
	        			if (tmp instanceof com.asf.nextreports.engine.queryexec.IdName) {
	        				com.asf.nextreports.engine.queryexec.IdName oldIdName = (com.asf.nextreports.engine.queryexec.IdName) tmp;
	        				IdName idName = new IdName();
	        				idName.setId(oldIdName.getId());
	        				idName.setName(oldIdName.getName());
	        				convertedValues[i] = idName;
	        				converted = true;
	        			} else {
	        				convertedValues[i] = tmp;
	        			}
	        		}
	        		
	        		if (converted) {
	        			ValueFactory valueFactory = node.getSession().getValueFactory();
	                    Binary binary = valueFactory.createBinary(new ByteArrayInputStream(serialize(convertedValues)));
	        			property.setValue(binary);
	        		}
	        	} else if (value instanceof com.asf.nextreports.engine.queryexec.IdName) {
    				com.asf.nextreports.engine.queryexec.IdName oldIdName = (com.asf.nextreports.engine.queryexec.IdName) value;
    				IdName idName = new IdName();
    				idName.setId(oldIdName.getId());
    				idName.setName(oldIdName.getName());

        			ValueFactory valueFactory = node.getSession().getValueFactory();
                    Binary binary = valueFactory.createBinary(new ByteArrayInputStream(serialize(idName)));
        			property.setValue(binary);
	        	}
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }
		
        getTemplate().save();
	}
1303210
@SuppressWarnings({ "unchecked", "rawtypes" })
    public static Object convert(Object source, Class<?> target) throws ConversionException {
        if (target == null) {
            throw new ConversionException("Unable to perform conversion, target was null");
        }
        if (source == null) {
            if (target.isPrimitive()) {
                throw new ConversionException(String.format("Unable to convert null to primitive value of %s", target));
            }
            return source;
        } else if ((source instanceof Float && ((Float) source).isNaN()) || (source instanceof Double && ((Double) source).isNaN())) {
            // Don't convert NaN values
            return source;
        }
        //		if (BaseConnection.class.isAssignableFrom(source.getClass()) && !target.equals(IConnection.class)) {
        //			log.debug("Conversion failure - source: {} target: {}", source.getClass(), target);
        //			throw new ConversionException("Source is not assignable and target is not equal to IConnection");
        //		}
        if (target.isInstance(source)) {
            return source;
        }
        if (target.isAssignableFrom(source.getClass())) {
            return source;
        }
        if (target.isArray()) {
            return convertToArray(source, target);
        }
        if (target.equals(String.class)) {
            return source.toString();
        }
        if (target.isPrimitive()) {
            return convertToWrappedPrimitive(source, primitiveMap.get(target));
        }
        if (wrapperMap.containsKey(target)) {
            return convertToWrappedPrimitive(source, target);
        }
        if (target.equals(Map.class)) {
            return convertBeanToMap(source);
        }
        if (target.equals(List.class) || target.equals(Collection.class)) {
            if (source.getClass().equals(LinkedHashMap.class)) {
                return convertMapToList((LinkedHashMap<?, ?>) source);
            } else if (source.getClass().isArray()) {
                return convertArrayToList((Object[]) source);
            }
        }
        if (target.equals(Set.class) && source.getClass().isArray()) {
            return convertArrayToSet((Object[]) source);
        }
        if (target.equals(Set.class) && source instanceof List) {
            return new HashSet((List) source);
        }
        if (source instanceof Map) {
            return convertMapToBean((Map) source, target);
        }
        throw new ConversionException(String.format("Unable to preform conversion from %s to %s", source, target));
    }
270640
@SuppressWarnings("rawtypes")
	@Override
	protected Object convertToType(Class type, Object value) throws Throwable {
		return new Text(value.toString());
	}
1303678
@SuppressWarnings("unchecked")
    public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException {
        return convert(fromValue, toType, (String) null);
    }
1170789
public <S, T> T convertTo(ConverterKey<S,T> key, Object object) {

		if (object == null) {
			return null;
		}
		
		Converter<S, T> conv = findConverter(key.getInputClass(), key.getOutputClass(), key.getQualifierAnnotation() == null ? DefaultBinding.class : key.getQualifierAnnotation());
		
		if (conv == null) {
			throw new NoConverterFoundException(key);
		}
		
		@SuppressWarnings("unchecked")
		S myObject = (S)object;
		return conv.convert(myObject);
	}
1053169
public <T> T convert(ConversionContext context, Object source,
			Class<T> clazz) throws ConverterException {
		return (T) convert(context, source, TypeReference.get(clazz));
	}
1048142
@Override
	public Object convert(String value, Class type) {
		if (isNullOrEmpty(value)) {
			return null;
		}

		if (Character.isDigit(value.charAt(0))) {
			return resolveByOrdinal(value, type);
		} else {
			return resolveByName(value, type);
		}
	}