值提供器转Bean

@param valueProvider 值提供器
@param bean Bean
768409
private void valueProviderToBean(ValueProvider<String> valueProvider, Object bean) {
		if (null == valueProvider) {
			return;
		}

		final CopyOptions copyOptions = this.copyOptions;
		Class<?> actualEditable = bean.getClass();
		if (copyOptions.editable != null) {
			// 检查限制类是否为target的父类或接口
			if (false == copyOptions.editable.isInstance(bean)) {
				throw new IllegalArgumentException(StrUtil.format("Target class [{}] not assignable to Editable class [{}]", bean.getClass().getName(), copyOptions.editable.getName()));
			}
			actualEditable = copyOptions.editable;
		}
		final HashSet<String> ignoreSet = (null != copyOptions.ignoreProperties) ? CollUtil.newHashSet(copyOptions.ignoreProperties) : null;
		final Map<String, String> fieldReverseMapping = copyOptions.getReversedMapping();

		final Collection<PropDesc> props = BeanUtil.getBeanDesc(actualEditable).getProps();
		String fieldName;
		Object value;
		Method setterMethod;
		Class<?> propClass;
		for (PropDesc prop : props) {
			// 获取值
			fieldName = prop.getFieldName();
			if (CollUtil.contains(ignoreSet, fieldName)) {
				// 目标属性值被忽略或值提供者无此key时跳过
				continue;
			}
			final String providerKey = mappingKey(fieldReverseMapping, fieldName);
			if (false == valueProvider.containsKey(providerKey)) {
				// 无对应值可提供
				continue;
			}
			setterMethod = prop.getSetter();
			if (null == setterMethod) {
				// Setter方法不存在跳过
				continue;
			}

			Type firstParamType = TypeUtil.getFirstParamType(setterMethod);
			if (firstParamType instanceof ParameterizedType) {
				// 参数为泛型参数类型，解析对应泛型类型为真实类型
				ParameterizedType tmp = (ParameterizedType) firstParamType;
				Type[] actualTypeArguments = tmp.getActualTypeArguments();
				if (TypeUtil.hasTypeVeriable(actualTypeArguments)) {
					// 泛型对象中含有未被转换的泛型变量
					actualTypeArguments = TypeUtil.getActualTypes(this.destType, setterMethod.getDeclaringClass(), tmp.getActualTypeArguments());
					if (ArrayUtil.isNotEmpty(actualTypeArguments)) {
						// 替换泛型变量为实际类型
						firstParamType = new ParameterizedTypeImpl(actualTypeArguments, tmp.getOwnerType(), tmp.getRawType());
					}
				}
			} else if (firstParamType instanceof TypeVariable) {
				// 参数为泛型，查找其真实类型（适用于泛型方法定义于泛型父类）
				firstParamType = TypeUtil.getActualType(this.destType, setterMethod.getDeclaringClass(), (TypeVariable<?>) firstParamType);
			}

			value = valueProvider.value(providerKey, firstParamType);
			if (null == value && copyOptions.ignoreNullValue) {
				continue;// 当允许跳过空时，跳过
			}
			if (bean.equals(value)) {
				continue;// 值不能为bean本身，防止循环引用
			}

			try {
				// valueProvider在没有对值做转换且当类型不匹配的时候，执行默认转换
				propClass = prop.getFieldClass();
				if (false == propClass.isInstance(value)) {
					value = Convert.convert(propClass, value);
					if (null == value && copyOptions.ignoreNullValue) {
						continue;// 当允许跳过空时，跳过
					}
				}

				// 执行set方法注入值
				setterMethod.invoke(bean, value);
			} catch (Exception e) {
				if (copyOptions.ignoreError) {
					continue;// 忽略注入失败
				} else {
					throw new UtilException(e, "Inject [{}] error!", prop.getFieldName());
				}
			}
		}
	}
248026
public static <V> void validateConfiguredValueType(Class<V> valueType, V value) throws ClassCastException {
        if (Object.class != valueType) {
            // means that type checks is required
            if (!valueType.isAssignableFrom(value.getClass())) {
                throw new ClassCastException("Value '" + value + "' is not assignable to " + valueType);
            }
        }
    }
984264
@Override
	public void updateBeanValue() {
		List<?> beanList = this.getBeanList();
		WComponent renderer = getRepeatedComponent();

		for (int i = 0; i < beanList.size(); i++) {
			Object rowData = beanList.get(i);
			UIContext rowContext = getRowContext(rowData, i);

			UIContextHolder.pushContext(rowContext);

			try {
				WebUtilities.updateBeanValue(renderer);
			} finally {
				UIContextHolder.popContext();
			}
		}
	}
834468
private _ValueReferenceWrapper getValueReference(
            final ValueExpression valueExpression, final FacesContext context)
    {
        ELContext elCtx = context.getELContext();
        if (_ExternalSpecifications.isUnifiedELAvailable())
        {
            // unified el 2.2 is available --> we can use ValueExpression.getValueReference()
            // we can't access ValueExpression.getValueReference() directly here, because
            // Class loading would fail in applications with el-api versions prior to 2.2
            _ValueReferenceWrapper wrapper = _BeanValidatorUELUtils.getUELValueReferenceWrapper(valueExpression, elCtx);
            if (wrapper != null)
            {
                if (wrapper.getProperty() == null)
                {
                    // Fix for issue in Glassfish EL-impl-2.2.3
                    if (firstValueReferenceWarning && log.isLoggable(Level.WARNING))
                    {
                        firstValueReferenceWarning = false;
                        log.warning("ValueReference.getProperty() is null. " +
                                    "Falling back to classic ValueReference resolving. " +
                                    "This fallback may hurt performance. " +
                                    "This may be caused by a bug your EL implementation. " +
                                    "Glassfish EL-impl-2.2.3 is known for this issue. " +
                                    "Try switching to a different EL implementation.");
                    }
                }
                else
                {
                    return wrapper;
                }
            }
        }

        // get base object and property name the "old-fashioned" way
        return _ValueReferenceResolver.resolve(valueExpression, elCtx);
    }
18192
protected final void beanUpdate(Object bean, Object identifier, Object value) {
        LOGGER.trace("Update bean \"" + bean + "\" property \"" + identifier + "\"");

        String propertyName = identifier.toString();

        Class beanType = bean.getClass();
        Class propType = PROPERTY_CACHE.getPropertyType(beanType, propertyName);
        // Get the type of the JavaBean property given reflected information from the JavaBean's type
        if(propType != null) {
            try {
                // The type of the JavaBean property is a List.  To update it, get the List and
                // append the value to the end of the List.
                if(List.class.isAssignableFrom(propType)) {
                    Method listGetter = PROPERTY_CACHE.getPropertyGetter(beanType, propertyName);
                    if(listGetter != null) {
                        List list = (List)listGetter.invoke(bean, (Object[])null);
                        applyValuesToList(value, list);
                        return;
                    }
                }
                // The JavaBean is an Object, so set the Bean's property with the given value
                else {
                    Method setter = PROPERTY_CACHE.getPropertySetter(beanType, propertyName);

                    if(setter != null) {
                        LOGGER.trace("Set property via setter method: [" + setter + "]");

                        Class targetType = setter.getParameterTypes()[0];
                        Object converted = ParseUtils.convertType(value, targetType);

                        setter.invoke(bean, new Object[]{converted});
                        return;
                    }
                }
            }
            catch(Exception e) {
                String msg = "Could not update proprety named \"" + propertyName + "\" on bean of type \"" + beanType + "\".  Cause: " + e;
                LOGGER.error(msg, e);
                throw new RuntimeException(msg, e);
            }
        }

        String msg = "Could not update expression because a public JavaBean setter for the property \"" + identifier + "\" could not be found.";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }
75035
protected T checkReturnValue(T instance) {
        if (instance == null && !isDependent()) {
            throw BeanLogger.LOG.nullNotAllowedFromProducer(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()));
        }
        if (instance == null) {
            InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek();
            if (injectionPoint != null) {
                Class<?> injectionPointRawType = Reflections.getRawType(injectionPoint.getType());
                if (injectionPointRawType.isPrimitive()) {
                    return cast(Defaults.getJlsDefaultValue(injectionPointRawType));
                }
            }
        }
        if (instance != null && !(instance instanceof Serializable)) {
            if (beanManager.isPassivatingScope(getScope())) {
                throw BeanLogger.LOG.nonSerializableProductError(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()));
            }
            InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek();
            if (injectionPoint != null && injectionPoint.getBean() != null && Beans.isPassivatingScope(injectionPoint.getBean(), beanManager)) {
                // Transient field is passivation capable injection point
                if (!(injectionPoint.getMember() instanceof Field) || !injectionPoint.isTransient()) {
                    throw BeanLogger.LOG.unserializableProductInjectionError(this, Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()),
                            injectionPoint, Formats.formatAsStackTraceElement(injectionPoint.getMember()));
                }
            }
        }
        return instance;
    }
455985
public void registerMultiValueProvider(MultiValueProvider multiValueProvider) {
    String name = multiValueProvider.getName();
    MultiValueProvider oldProvider = multiValues.put(name, multiValueProvider);
    if (oldProvider != null) {
      LOGGER.warn("MultiValueProvider [{}] @{} has been replaced by [{}]!",
        oldProvider,
        multiValueProvider.getName(),
        multiValueProvider);
    }
    notifyReportableObservers(multiValueProvider);
  }
832837
protected Object resolveProviderConfig(String exp, Map<String, ? extends Object> contextMap, LaContainer container,
            Class<?> resultType) {
        if (exp.startsWith(PROVIDER_GET) && exp.endsWith(METHOD_MARK) && exp.contains(".") && !exp.contains("\"")) {
            final String[] tokens = exp.split("\\.");
            if (tokens.length > 1) {
                Object component = null;
                BeanDesc beanDesc = null;
                for (String prop : tokens) {
                    if (prop.endsWith(METHOD_MARK)) { // method
                        if (component == null) { // e.g. getJdbcUrl() only
                            break;
                        }
                        final String methodName = prop.substring(0, prop.length() - METHOD_MARK.length());
                        component = beanDesc.invoke(component, methodName, (Object[]) null);
                        beanDesc = BeanDescFactory.getBeanDesc(component.getClass());
                    } else { // component or property
                        if (beanDesc == null) { // first element
                            if (container.hasComponentDef(prop)) { // component
                                component = container.getComponent(prop);
                                beanDesc = BeanDescFactory.getBeanDesc(component.getClass());
                            } else {
                                break;
                            }
                        } else { // next elements, property
                            final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(prop);
                            if (propertyDesc != null) {
                                component = propertyDesc.getValue(component);
                                beanDesc = BeanDescFactory.getBeanDesc(component.getClass());
                            } else {
                                break;
                            }
                        }
                    }
                }
                if (component != null) {
                    return component;
                }
            }
        }
        return null;
    }
244259
public static void setProperty(Object bean, String propertyName, Object value)
   {
	   setProperty(bean,propertyName,value,true);
   }
1041489
public static void setProperty(Object bean, String expression, Object value) {
		BeanPath.create(expression).set(bean, value);
	}
925151
@Override
	public void setBeanId(final Object beanId) {
		BeanAndProviderBoundComponentModel model = getOrCreateComponentModel();
		model.setBeanId(beanId);
		// Remove values in scratch map
		removeBeanFromScratchMap();
	}
491181
public static void setValueFor(final ConverterFactory converterFactory, final InputComponent<?, ?> component,
            final Object value)
   {
      if (component instanceof SingleValued)
      {
         setSingleInputValue(converterFactory, component, value, false);
      }
      else if (component instanceof ManyValued)
      {
         setManyInputValue(converterFactory, component, value, false);
      }
   }
824081
protected @Nonnull <T> Provider<T> getBeanProvider(@Nullable BeanResolutionContext resolutionContext, @Nonnull Class<T> beanType) {
        return getBeanProvider(resolutionContext, beanType, null);
    }
961013
public void mapping(Object src, Object target) throws BeanMappingException {
        boolean first = ContextObjectHolder.getInstance().enter();
        boolean isBeanMappingSupportScript = BeanMappingEnvironment.isBeanMappingSupportScript();
        BeanMappingParam param = new BeanMappingParam();
        param.setSrcRef(src);
        param.setTargetRef(target);
        param.setConfig(this.config);
        List<ValueProcess> vps = BeanMappingEnvironment.getBeanMappingVps();
        param.setProcesses(vps);

        // 执行mapping处理
        try {
            BeanMappingExecutor.execute(param);
        } finally {
            if (first) {// 第一个进入的负责清空数据，可能存在递归调用处理
                ContextObjectHolder.getInstance().clear();
                if (isBeanMappingSupportScript) {
                    ScriptHelper.getInstance().getScriptExecutor().disposeFunctions();// 清空记录
                }
            }
        }
    }
1185543
@Override
  public Object getValue(final String optionObjectName,
                         final String optionName) throws OptionsException {
    if (useSystemwideValues) {
      // No screwing round with them
      throw new OptionsException("cannot.set.values");
    }

    try {
      /* Find the bean */
      Object opts = getProperty(optionObjectName);

      /* ... and its getter */
      Method meth = findGetter(opts, optionName);

      /* ... now the value */
      return meth.invoke(opts, (Object[])null);
    } catch (OptionsException ce) {
      throw ce;
    } catch (Throwable t) {
      throw new OptionsException(t);
    }
  }
211501
public Object[] resolve(final Invocation inv,
            final ParameterBindingResult parameterBindingResult) throws Exception {
        Object[] parameters = new Object[paramMetaDatas.length];
        for (int i = 0; i < resolvers.length; i++) {
            if (resolvers[i] == null) {
                continue;
            }
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Resolves parameter "
                            + paramMetaDatas[i].getParamType().getSimpleName() + " using "
                            + resolvers[i].getClass().getName());
                }
                parameters[i] = resolvers[i].resolve(inv, paramMetaDatas[i]);
                // afterPropertiesSet
                if (parameters[i] instanceof InitializingBean) {
                    ((InitializingBean) parameters[i]).afterPropertiesSet();
                }
                if (parameters[i] == null) {
                    DefValue defValudeAnnotation = paramMetaDatas[i].getAnnotation(DefValue.class);
                    if (defValudeAnnotation != null && paramMetaDatas[i].getParamType() == String.class) {
                        parameters[i] = defValudeAnnotation.value();
                    }
                }
            } catch (TypeMismatchException e) {
                // 出现这个错误肯定是解析一般参数失败导致的，而非bean里面的某个属性值的解析失败

                logger.debug("", e);

                // 对简单类型的参数，设置一个默认值给它以支持对该方法的继续调用
                if (paramMetaDatas[i].getParamType().isPrimitive()) {
                    DefValue defValudeAnnotation = paramMetaDatas[i].getAnnotation(DefValue.class);
                    if (defValudeAnnotation == null
                            || DefValue.NATIVE_DEFAULT.equals(defValudeAnnotation.value())) {
                        // 对这最常用的类型做一下if-else判断，其他类型就简单使用converter来做吧
                        if (paramMetaDatas[i].getParamType() == int.class) {
                            parameters[i] = Integer.valueOf(0);
                        } else if (paramMetaDatas[i].getParamType() == long.class) {
                            parameters[i] = Long.valueOf(0);
                        } else if (paramMetaDatas[i].getParamType() == boolean.class) {
                            parameters[i] = Boolean.FALSE;
                        } else if (paramMetaDatas[i].getParamType() == double.class) {
                            parameters[i] = Double.valueOf(0);
                        } else if (paramMetaDatas[i].getParamType() == float.class) {
                            parameters[i] = Float.valueOf(0);
                        } else {
                            TypeConverter typeConverter = SafedTypeConverterFactory
                                    .getCurrentConverter();
                            parameters[i] = typeConverter.convertIfNecessary("0", paramMetaDatas[i]
                                    .getParamType());
                        }
                    } else {
                        TypeConverter typeConverter = SafedTypeConverterFactory
                                .getCurrentConverter();
                        parameters[i] = typeConverter.convertIfNecessary(defValudeAnnotation
                                .value(), paramMetaDatas[i].getParamType());
                    }
                }
                // 
                String paramName = parameterNames[i];
                if (paramName == null) {
                    for (String name : paramMetaDatas[i].getParamNames()) {
                        if ((paramName = name) != null) {
                            break;
                        }
                    }
                }
                Assert.isTrue(paramName != null);
                FieldError fieldError = new FieldError(//
                        "method", // 该出错字段所在的对象的名字；对于这类异常我们统一规定名字为method
                        paramName, // 出错的字段的名字；取其参数名
                        inv.getParameter(paramName), // 被拒绝的值
                        true,//whether this error represents a binding failure (like a type mismatch); else, it is a validation failure
                        new String[] { e.getErrorCode() },// "typeMismatch"
                        new String[] { inv.getParameter(paramName) }, //the array of arguments to be used to resolve this message
                        null // the default message to be used to resolve this message
                );
                parameterBindingResult.addError(fieldError);
            } catch (Exception e) {
                // 什么错误呢？比如很有可能是构造对象不能成功导致的错误，没有默认构造函数、构造函数执行失败等等
                logger.error("", e);
                throw e;
            }
        }
        return parameters;
    }
957768
public static BeanDefinitionHolder registerBean(String beanId, BeanDefinition beanDefinition, ParserContext parserContext, boolean shouldFireEvents) {
        if (parserContext.getRegistry().containsBeanDefinition(beanId)) {
            return new BeanDefinitionHolder(parserContext.getRegistry().getBeanDefinition(beanId), beanId);
        }

        BeanDefinitionHolder configurationHolder = new BeanDefinitionHolder(beanDefinition, beanId);
        BeanDefinitionReaderUtils.registerBeanDefinition(configurationHolder, parserContext.getRegistry());

        if (shouldFireEvents) {
            BeanComponentDefinition componentDefinition = new BeanComponentDefinition(configurationHolder);
            parserContext.registerComponent(componentDefinition);
        }

        return configurationHolder;
    }