Optional apply()

in src/main/java/com/microsoft/azure/functions/worker/binding/DataOperations.java [83:123]


	Optional<R> apply(T sourceValue, Type targetType) {
		Optional<R> resultValue = null;

		if (sourceValue != null) {
			CheckedBiFunction<T, Type, R> matchingOperation = this.operations
					.get(TypeUtils.getRawType(targetType, null));
			if (matchingOperation != null) {
				resultValue = Optional.ofNullable(matchingOperation).map(op -> op.tryApply(sourceValue, targetType));
			} else {		
			  String sourceData;
			  Class<?> sourceValueClass = sourceValue.getClass();
			  if (sourceValueClass.isAssignableFrom(byte[].class)) {
			    sourceData = new String((byte[]) sourceValue);			      
			  }
			  else
			  {
			    sourceData = (String) sourceValue;
			  }
			  
				// Try POJO
				if (Collection.class.isAssignableFrom(TypeUtils.getRawType(targetType, null))) {
					Class<?> collectionItemType = (Class<?>) CoreTypeResolver
							.getParameterizedActualTypeArgumentsType(targetType);

					try {
						Object objList = toList(sourceData, collectionItemType);
						resultValue = (Optional<R>) Optional.ofNullable(objList);
					} catch (Exception jsonParseEx) {
						resultValue = convertFromJson(sourceData, targetType);
					}
				} else {
					resultValue = convertFromJson(sourceData, TypeUtils.getRawType(targetType, null));
				}
			}
		}

		if (resultValue == null || !resultValue.isPresent()) {
			resultValue = ((Optional<R>) Optional.ofNullable(generalAssignment(sourceValue, targetType)));
		}
		return resultValue;
	}