ServletRequest 参数转Bean

@param <T> Bean类型
@param beanClass Bean Class
@param valueProvider 值提供者
@param copyOptions 拷贝选项，见 {@link CopyOptions}
@return Bean
762054
public static <T> T toBean(Class<T> beanClass, ValueProvider<String> valueProvider, CopyOptions copyOptions) {
		return fillBean(ReflectUtil.newInstance(beanClass), valueProvider, copyOptions);
	}
178612
public static <T> void initSingletonEJBCDIProvider(AbstractResourceInfo resource, Message message, T resourceObject) {

        /*
         * Only @Provider will use logic here.
         * As EJB can only be default constructor, CDI can be default constructor or 1 param with @Inject constructor
         * And a provider must have 1 public constructor(default constructor or @Context params constructor)
         * then the intersection is only default constructor.
         * so if ConstructorProxies!=null means there are some other invalid constructors to EJB or CDI container
         */
        if ((!(resource instanceof ProviderInfo)) || (resource instanceof ApplicationInfo) || resource.getConstructorProxies() != null) {
            return;
        }

        ProviderInfo<T> pi = (ProviderInfo<T>) resource;

        /**
         * if this provider is inited which means it may be replaced by EJB or CDI bean or it may be invoked with @PostConstrcut
         */
        if (pi.isInit()) {
            return;
        }

        synchronized(pi) {
            if (pi.isInit()) {
                return;
            }
            Class clz = pi.getProvider().getClass();
            Bus bus = resource.getBus();

            if (bus != null) { // if bus is null, then we don't need to do injection on this provider
                List<JaxRsFactoryBeanCustomizer> beanCustomizers = (List<JaxRsFactoryBeanCustomizer>) bus.getProperty(JaxRsConstants.ENDPOINT_LIST_BEANCUSTOMIZER);
                Map<String, Object> beanCustomizerContexts = (Map<String, Object>) bus.getProperty(JaxRsConstants.ENDPOINT_BEANCUSTOMIZER_CONTEXTOBJ);

                if (beanCustomizers != null && !beanCustomizers.isEmpty() && beanCustomizerContexts != null) {

                    Object newProviderInstance = null;
                    for (JaxRsFactoryBeanCustomizer beanCustomizer : beanCustomizers) {
                        if (beanCustomizer.isCustomizableBean(clz, beanCustomizerContexts.get(Integer.toString(beanCustomizer.hashCode())))) {

                            newProviderInstance = beanCustomizer.onSingletonProviderInit(pi.getProvider(), beanCustomizerContexts.get(Integer.toString(beanCustomizer.hashCode())), message);

                            /**
                             * if newProviderInstance!= the original object, which means it is replaced to EJB or CDI, so just return
                             * no need call @PostConstruct
                             */
                            if (newProviderInstance != null) {
                                //call setProvider to set isInit==true
                                pi.setProvider(newProviderInstance);
                                pi.setIsInit(true);
                                return;
                            }
                        }
                    }
                }
                //No replacement happens which means this is a POJO, call @PostConstruct
                pi.setIsInit(true);
                Method postConstructMethod = ResourceUtils.findPostConstructMethod(clz);
                InjectionUtils.invokeLifeCycleMethod(pi.getProvider(), postConstructMethod);
            }
        }
    }
265324
@SuppressWarnings({ "unchecked", "rawtypes" })
    public <T> B option(ClientOptionValue<T> optionValue) {
        requireNonNull(optionValue, "optionValue");
        final ClientOption<?> opt = optionValue.option();
        if (opt == ClientOption.DECORATION) {
            final ClientDecoration d = (ClientDecoration) optionValue.value();
            d.entries().forEach(e -> decoration.add0(e.requestType(), e.responseType(),
                                                     (Function) e.decorator()));
        } else if (opt == ClientOption.HTTP_HEADERS) {
            final HttpHeaders h = (HttpHeaders) optionValue.value();
            setHttpHeaders(h);
        } else {
            options.put(opt, optionValue);
        }
        return self();
    }
987106
private static Object fillBean(final OptionVisitor visitor, final Type type, final Object bean, final List<ParameterMetadata> metadatas) {
        if (!Class.class.isInstance(type)) { // can't do anything
            return null;
        }

        List<Object> constructorParam = bean == null ? new ArrayList<>() : null;
        try {
            final Constructor constructor = Class.class.cast(type).getConstructors()[0];
            final BeanInfo descriptor = Introspector.getBeanInfo(Class.class.cast(type));
            final Map<String, PropertyDescriptor> descriptorMap = new HashMap<>();
            for (final PropertyDescriptor d : descriptor.getPropertyDescriptors()) {
                descriptorMap.put(d.getName(), d);
            }
            Object value = bean;
            int consIdx = -1;
            for (final ParameterMetadata metadata : metadatas) {
                consIdx++;
                if (metadata.getType() != ParameterMetadata.ParamType.OPTION) { // we support only 1 level for now
                    continue;
                }


                final String name = metadata.getName().substring(metadata.getName().lastIndexOf('.') + 1);
                if (!descriptorMap.containsKey(name)) {
                    continue;
                }

                final PropertyDescriptor propertyDescriptor = descriptorMap.get(name);
                if (propertyDescriptor == null) {
                    continue;
                }

                if (bean != null) { // check it is not already set
                    final Method readMethod = propertyDescriptor.getReadMethod();
                    if (readMethod == null) {
                        continue;
                    }
                    try {
                        final Object val = readMethod.invoke(bean);
                        if (val != null) {
                            continue;
                        }
                    } catch (final IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    } catch (InvocationTargetException e) {
                        throw new IllegalStateException(e.getCause());
                    }
                }

                final Method write = propertyDescriptor.getWriteMethod();
                if (write != null) {
                    final Object val = visitor.onOption(consIdx, metadata, new AnnotatedElementImpl(write.getParameterAnnotations()[0]));
                    if (val != null) {
                        try {
                            if (value == null) {
                                constructorParam.add(val);
                            } else {
                                write.invoke(value, val);
                            }
                        } catch (final IllegalAccessException e) {
                            throw new IllegalStateException(e);
                        } catch (final InvocationTargetException e) {
                            throw new IllegalStateException(e.getCause());
                        }
                    }

                }
            }
            if (value == null) {
                try {
                    value = constructor.newInstance(constructorParam.toArray(new Object[constructorParam.size()]));
                } catch (final IllegalAccessException e) {
                    throw new IllegalStateException(e);
                } catch (final InstantiationException e) {
                    throw new IllegalStateException(e);
                } catch (final InvocationTargetException e) {
                    throw new IllegalStateException(e.getCause());
                }
            }
            return value;
        } catch (final IntrospectionException e) {
            throw new IllegalStateException(e);
        }
    }
266003
public BeanMappingObject getBeanMappingObject(Class src, Class target) {
        return getFromRepository(src, target, this.repository);
    }
981741
public static <T> T copy(Object src, T dest, boolean setDefaultValForNull) throws BeanConverterException {
        if (src == null)
            return null;

        try {
            Class<? extends Object> destClass = dest.getClass();
            Map<String, PropertyDescriptor> srcDescriptors = getCachePropertyDescriptors(src.getClass());
            Map<String, PropertyDescriptor> destDescriptors = getCachePropertyDescriptors(destClass);

            Set<String> keys = destDescriptors.keySet();
            for (String key : keys) {
                PropertyDescriptor srcDescriptor = srcDescriptors.get(key);

                if (srcDescriptor == null)
                    continue;

                PropertyDescriptor destDescriptor = destDescriptors.get(key);

                Object value = srcDescriptor.getReadMethod().invoke(src);

                Class<?> propertyType = destDescriptor.getPropertyType();

                Method writeMethod = destDescriptor.getWriteMethod();
                if (writeMethod == null) {
                    String name = destDescriptor.getName();
                    try {
                        writeMethod = destClass.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), destDescriptor.getPropertyType());

                        destDescriptor.setWriteMethod(writeMethod);
                    } catch (Exception e) {
                    }
                }
                if (writeMethod != null) {
                    //类型匹配
                    boolean matched = propertyType == srcDescriptor.getPropertyType();
                    if (!matched) {
                    	
                        if (value != null || setDefaultValForNull) {
                        	if(isSimpleDataType(srcDescriptor)){                        		
                        		value = toValue(srcDescriptor, value, propertyType);
                        	}else{
                        		value = copy(value, propertyType);
                        	}
                        }
                    }
                    //设置默认值
                    if (value == null && setDefaultValForNull) {
                        if (destDescriptor.getPropertyType() == Long.class || destDescriptor.getPropertyType() == Integer.class || destDescriptor.getPropertyType() == Short.class || destDescriptor.getPropertyType() == Double.class || destDescriptor.getPropertyType() == Float.class) {
                            value = 0;
                        } else if (destDescriptor.getPropertyType() == String.class) {
                            value = "";
                        } else if (destDescriptor.getPropertyType() == BigDecimal.class) {
                            value = new BigDecimal("0");
                        }
                    }

                    if (value != null) {
                        writeMethod.invoke(dest, value);
                    }
                }
            }

            return dest;
        } catch (Exception e) {
            throw new BeanConverterException(e);
        }
    }
146903
private static List<PropertyDescriptor> getPropertyDescriptorsOptional(
        Class<?> beanClass)
    {
        BeanInfo beanInfo = getBeanInfoOptional(beanClass);
        if (beanInfo == null)
        {
            return Collections.emptyList();
        }
        PropertyDescriptor propertyDescriptors[] = 
            beanInfo.getPropertyDescriptors();
        if (propertyDescriptors == null)
        {
            return Collections.emptyList();
        }
        return Collections.unmodifiableList(
            new ArrayList<PropertyDescriptor>(
                Arrays.asList(propertyDescriptors)));
    }
1278297
public static ConfigurationOptionBuilder<List<URL>> urlsOption() {
		return new ConfigurationOptionBuilder<List<URL>>(new ListValueConverter<URL>(UrlValueConverter.INSTANCE), List.class)
				.defaultValue(Collections.<URL>emptyList());
	}
286732
@Override
    public BeanBuilder<B> set(String propertyName, Object value) {
        return set(metaBean.metaProperty(propertyName), value);
    }
293254
public static void copy(Object src, Object target) throws BeanMappingException {
        BeanCopy copy = BeanCopy.create(src.getClass(), target.getClass());
        copy.copy(src, target);
    }
657816
public static <T> T toBean(Object source, Class<T> clazz) {
		final T target = ReflectUtil.newInstance(clazz);
		copyProperties(source, target);
		return target;
	}
1275371
public BeanMappingObject getBeanMapObject(Class src, Class target, boolean autoRegister) {
        BeanMappingObject object = autoRepository.getBeanMappingObject(src, target);
        if (object == null && autoRegister) {
            if (isMap(src)) {// 判断是否为map接口的子类
                autoRepository.registerMap(target);
            } else {
                autoRepository.registerMap(src);
            }

            object = getFromRepository(src, target, this.autoRepository);
        }
        return object;
    }
1239406
@EachBean(ServiceHttpClientConfiguration.class)
    @Requires(condition = ServiceHttpClientCondition.class)
    DefaultHttpClient serviceHttpClient(
            @Parameter ServiceHttpClientConfiguration configuration,
            @Parameter StaticServiceInstanceList instanceList) {
        List<URI> originalURLs = configuration.getUrls();
        Collection<URI> loadBalancedURIs = instanceList.getLoadBalancedURIs();
        boolean isHealthCheck = configuration.isHealthCheck();

        LoadBalancer loadBalancer = loadBalancerFactory.create(instanceList);

        Optional<String> path = configuration.getPath();
        DefaultHttpClient httpClient;
        if (path.isPresent()) {
            httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration, path.get());
        } else {
            httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration);
        }

        httpClient.setClientIdentifiers(configuration.getServiceId());

        if (isHealthCheck) {
            taskScheduler.scheduleWithFixedDelay(configuration.getHealthCheckInterval(), configuration.getHealthCheckInterval(), () -> Flowable.fromIterable(originalURLs).flatMap(originalURI -> {
                URI healthCheckURI = originalURI.resolve(configuration.getHealthCheckUri());
                return httpClient.exchange(HttpRequest.GET(healthCheckURI)).onErrorResumeNext(throwable -> {
                    if (throwable instanceof HttpClientResponseException) {
                        HttpClientResponseException responseException = (HttpClientResponseException) throwable;
                        HttpResponse response = responseException.getResponse();
                        //noinspection unchecked
                        return Flowable.just(response);
                    }
                    return Flowable.just(HttpResponse.serverError());
                }).map(response -> Collections.singletonMap(originalURI, response.getStatus()));
            }).subscribe(uriToStatusMap -> {
                Map.Entry<URI, HttpStatus> entry = uriToStatusMap.entrySet().iterator().next();

                URI uri = entry.getKey();
                HttpStatus status = entry.getValue();

                if (status.getCode() >= 300) {
                    loadBalancedURIs.remove(uri);
                } else if (!loadBalancedURIs.contains(uri)) {
                    loadBalancedURIs.add(uri);
                }
            }));
        }
        return httpClient;
    }
805770
public static void copyProperty(Object bean, String name, Object value)
            throws Excel4JException {

        if (null == name || null == value)
            return;
        Field field = matchClassField(bean.getClass(), name);
        if (null == field)
            return;
        Method method;
        try {
            method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER);

            if (value.getClass() == field.getType()) {
                method.invoke(bean, value);
            } else {
                method.invoke(bean, str2TargetClass(value.toString(), field.getType()));
            }
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            throw new Excel4JException(e);
        }

    }
1062925
private Optional<MapPositionSetter> createField(final Class<?> beanClass, final String fieldName) {
        
        final String positionFieldName = fieldName + "Position";
        
        final Field positionField;
        try {
            positionField = beanClass.getDeclaredField(positionFieldName);
            positionField.setAccessible(true);
            
        } catch (NoSuchFieldException | SecurityException e) {
            return Optional.empty();
        }
        
        if(!Map.class.isAssignableFrom(positionField.getType())) {
            return Optional.empty();
        }
        
        final ParameterizedType type = (ParameterizedType) positionField.getGenericType();
        final Class<?> keyType = (Class<?>) type.getActualTypeArguments()[0];
        final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[1];
        
        if(keyType.equals(String.class) && valueType.equals(CellPosition.class)) {
            
            return Optional.of(new MapPositionSetter() {
                
                @SuppressWarnings("unchecked")
                @Override
                public void set(final Object beanObj, final CellPosition position, final String key) {
                    ArgUtils.notNull(beanObj, "beanObj");
                    ArgUtils.notNull(position, "position");
                    
                   try {
                       Map<String, CellPosition> positionMapObj = (Map<String, CellPosition>) positionField.get(beanObj);
                       if(positionMapObj == null) {
                           positionMapObj = new LinkedHashMap<>();
                           positionField.set(beanObj, positionMapObj);
                       }
                       
                       positionMapObj.put(key, position);
                       
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException("fail access position field.", e);
                    }
                }
            });
            
        } else if(keyType.equals(String.class) && valueType.equals(Point.class)) {
            
            return Optional.of(new MapPositionSetter() {
                
                @SuppressWarnings("unchecked")
                @Override
                public void set(final Object beanObj, final CellPosition position, final String key) {
                    ArgUtils.notNull(beanObj, "beanObj");
                    ArgUtils.notNull(position, "position");
                    
                    try {
                        Map<String, Point> positionMapObj = (Map<String, Point>) positionField.get(beanObj);
                        if(positionMapObj == null) {
                            positionMapObj = new LinkedHashMap<>();
                            positionField.set(beanObj, positionMapObj);
                        }
                        
                        
                        positionMapObj.put(key, position.toPoint());
                        
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException("fail access position field.", e);
                    }
                }
            });
            
        } else if(keyType.equals(String.class) && valueType.equals(CellAddress.class)) {
            
            return Optional.of(new MapPositionSetter() {
                
                @SuppressWarnings("unchecked")
                @Override
                public void set(final Object beanObj, final CellPosition position, final String key) {
                    ArgUtils.notNull(beanObj, "beanObj");
                    ArgUtils.notNull(position, "position");
                    
                    try {
                        Map<String, CellAddress> positionMapObj = (Map<String, CellAddress>) positionField.get(beanObj);
                        if(positionMapObj == null) {
                            positionMapObj = new LinkedHashMap<>();
                            positionField.set(beanObj, positionMapObj);
                        }
                        
                        
                        positionMapObj.put(key, position.toCellAddress());
                        
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException("fail access position field.", e);
                    }
                }
            });
        
        }
        
        return Optional.empty();
    }
182145
@Override public Set<R> getValueFromBean(D bean) throws IllegalBioPAXArgumentException
	{
		Object value = null;
		try
		{
			if (this.getDomain().isInstance(bean)) value = this.getMethod.invoke(bean);
		}
		catch (IllegalAccessException e)
		{
			throw new IllegalBioPAXArgumentException(
					"Could not invoke get method " + getMethod.getName() + " for " + bean, e);
		}
		catch (IllegalArgumentException e)
		{
			throw new IllegalBioPAXArgumentException(
					"Could not invoke get method " + getMethod.getName() + " for " + bean, e);
		}

		catch (InvocationTargetException e)
		{
			throw new IllegalBioPAXArgumentException(
					"Could not invoke get method " + getMethod.getName() + " for " + bean, e);
		}

		if (value == null) return Collections.emptySet();
		else if (this.isMultipleCardinality())
		{
			return (Collections.unmodifiableSet(((Set<R>) value)));
		} else
		{
			return Collections.singleton(((R) value));
		}
	}
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);
    }