Search in sources :

Example 51 with BeanInfo

use of java.beans.BeanInfo in project synergic-developing by zeemood.

the class Converters method convert.

/**
 * 使用指定 的读取器去转换字符串为对象。
 *
 * @param <T> 领域泛型
 * @param clazz 领域类型
 * @param reader 读取器
 * @return 领域对象
 * @throws ApiException
 */
public static <T> T convert(Class<T> clazz, Reader reader) throws AlipayApiException {
    T rsp = null;
    try {
        rsp = clazz.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        boolean isResponseClazz = AlipayResponse.class.isAssignableFrom(clazz);
        for (PropertyDescriptor pd : pds) {
            Method writeMethod = pd.getWriteMethod();
            if (writeMethod == null) {
                // ignore read-only fields
                continue;
            }
            String itemName = pd.getName();
            String listName = null;
            // 之前errorCode的属性要剔除掉
            if (isResponseClazz && excludeFields.contains(itemName)) {
                continue;
            }
            List<AlipayFieldMethod> alipayFieldMethods = new ArrayList<AlipayFieldMethod>();
            if (baseFields.contains(itemName) && isResponseClazz) {
                Field field = AlipayResponse.class.getDeclaredField(itemName);
                AlipayFieldMethod alipayFieldMethod = new AlipayFieldMethod();
                alipayFieldMethod.setField(field);
                // writeMethod属于父类,则直接使用
                if (writeMethod.getDeclaringClass().getName().contains("AlipayResponse")) {
                    alipayFieldMethod.setMethod(writeMethod);
                } else {
                    // 否则从父类再取一次
                    writeMethod = tryGetSetMethod(AlipayResponse.class, field, writeMethod.getName());
                    if (writeMethod == null) {
                        continue;
                    }
                    alipayFieldMethod.setMethod(writeMethod);
                }
                alipayFieldMethods.add(alipayFieldMethod);
                // 如果被子类覆盖的,则从尝试从子类中获取
                if (overideFields.contains(itemName)) {
                    field = tryGetFieldWithoutExp(clazz, itemName);
                    // 属性存在则需要重新从子类获取访问方法
                    if (field != null) {
                        writeMethod = tryGetSetMethod(clazz, field, writeMethod.getName());
                        if (writeMethod == null) {
                            continue;
                        }
                        alipayFieldMethod = new AlipayFieldMethod();
                        alipayFieldMethod.setField(field);
                        alipayFieldMethod.setMethod(writeMethod);
                        alipayFieldMethods.add(alipayFieldMethod);
                    }
                }
            } else {
                Field field = clazz.getDeclaredField(itemName);
                AlipayFieldMethod alipayFieldMethod = new AlipayFieldMethod();
                alipayFieldMethod.setField(field);
                alipayFieldMethod.setMethod(writeMethod);
                alipayFieldMethods.add(alipayFieldMethod);
            }
            // 迭代设置属性
            for (AlipayFieldMethod alipayFieldMethod : alipayFieldMethods) {
                Field field = alipayFieldMethod.getField();
                Method method = alipayFieldMethod.getMethod();
                ApiField jsonField = field.getAnnotation(ApiField.class);
                if (jsonField != null) {
                    itemName = jsonField.value();
                }
                ApiListField jsonListField = field.getAnnotation(ApiListField.class);
                if (jsonListField != null) {
                    listName = jsonListField.value();
                }
                if (!reader.hasReturnField(itemName)) {
                    if (listName == null || !reader.hasReturnField(listName)) {
                        // ignore non-return field
                        continue;
                    }
                }
                Class<?> typeClass = field.getType();
                // 目前
                if (String.class.isAssignableFrom(typeClass)) {
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof String) {
                        method.invoke(rsp, value.toString());
                    } else {
                        if (isCheckJsonType && value != null) {
                            throw new AlipayApiException(itemName + " is not a String");
                        }
                        if (value != null) {
                            method.invoke(rsp, value.toString());
                        } else {
                            method.invoke(rsp, "");
                        }
                    }
                } else if (Long.class.isAssignableFrom(typeClass)) {
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof Long) {
                        method.invoke(rsp, (Long) value);
                    } else {
                        if (isCheckJsonType && value != null) {
                            throw new AlipayApiException(itemName + " is not a Number(Long)");
                        }
                        if (StringUtils.isNumeric(value)) {
                            method.invoke(rsp, Long.valueOf(value.toString()));
                        }
                    }
                } else if (Integer.class.isAssignableFrom(typeClass)) {
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof Integer) {
                        method.invoke(rsp, (Integer) value);
                    } else {
                        if (isCheckJsonType && value != null) {
                            throw new AlipayApiException(itemName + " is not a Number(Integer)");
                        }
                        if (StringUtils.isNumeric(value)) {
                            method.invoke(rsp, Integer.valueOf(value.toString()));
                        }
                    }
                } else if (Boolean.class.isAssignableFrom(typeClass)) {
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof Boolean) {
                        method.invoke(rsp, (Boolean) value);
                    } else {
                        if (isCheckJsonType && value != null) {
                            throw new AlipayApiException(itemName + " is not a Boolean");
                        }
                        if (value != null) {
                            method.invoke(rsp, Boolean.valueOf(value.toString()));
                        }
                    }
                } else if (Double.class.isAssignableFrom(typeClass)) {
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof Double) {
                        method.invoke(rsp, (Double) value);
                    } else {
                        if (isCheckJsonType && value != null) {
                            throw new AlipayApiException(itemName + " is not a Double");
                        }
                    }
                } else if (Number.class.isAssignableFrom(typeClass)) {
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof Number) {
                        method.invoke(rsp, (Number) value);
                    } else {
                        if (isCheckJsonType && value != null) {
                            throw new AlipayApiException(itemName + " is not a Number");
                        }
                    }
                } else if (Date.class.isAssignableFrom(typeClass)) {
                    DateFormat format = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT);
                    format.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
                    Object value = reader.getPrimitiveObject(itemName);
                    if (value instanceof String) {
                        method.invoke(rsp, format.parse(value.toString()));
                    }
                } else if (List.class.isAssignableFrom(typeClass)) {
                    Type fieldType = field.getGenericType();
                    if (fieldType instanceof ParameterizedType) {
                        ParameterizedType paramType = (ParameterizedType) fieldType;
                        Type[] genericTypes = paramType.getActualTypeArguments();
                        if (genericTypes != null && genericTypes.length > 0) {
                            if (genericTypes[0] instanceof Class<?>) {
                                Class<?> subType = (Class<?>) genericTypes[0];
                                List<?> listObjs = reader.getListObjects(listName, itemName, subType);
                                if (listObjs != null) {
                                    method.invoke(rsp, listObjs);
                                }
                            }
                        }
                    }
                } else {
                    Object obj = reader.getObject(itemName, typeClass);
                    if (obj != null) {
                        method.invoke(rsp, obj);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new AlipayApiException(e);
    }
    return rsp;
}
Also used : BeanInfo(java.beans.BeanInfo) ArrayList(java.util.ArrayList) ParameterizedType(java.lang.reflect.ParameterizedType) Field(java.lang.reflect.Field) AlipayApiException(com.alipay.api.AlipayApiException) ArrayList(java.util.ArrayList) List(java.util.List) PropertyDescriptor(java.beans.PropertyDescriptor) Method(java.lang.reflect.Method) AlipayApiException(com.alipay.api.AlipayApiException) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) AlipayResponse(com.alipay.api.AlipayResponse) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat)

Example 52 with BeanInfo

use of java.beans.BeanInfo in project hibernate-orm by hibernate.

the class ConnectionProviderInitiator method initiateService.

@Override
public ConnectionProvider initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
    final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy(configurationValues);
    if (strategy == MultiTenancyStrategy.DATABASE || strategy == MultiTenancyStrategy.SCHEMA) {
        // nothing to do, but given the separate hierarchies have to handle this here.
        return null;
    }
    final StrategySelector strategySelector = registry.getService(StrategySelector.class);
    final Object explicitSetting = configurationValues.get(AvailableSettings.CONNECTION_PROVIDER);
    if (explicitSetting != null) {
        // if we are explicitly supplied a ConnectionProvider to use (in some form) -> use it..
        if (explicitSetting instanceof ConnectionProvider) {
            return (ConnectionProvider) explicitSetting;
        } else if (explicitSetting instanceof Class) {
            final Class providerClass = (Class) explicitSetting;
            LOG.instantiatingExplicitConnectionProvider(providerClass.getName());
            return instantiateExplicitConnectionProvider(providerClass);
        } else {
            String providerName = StringHelper.nullIfEmpty(explicitSetting.toString());
            if (providerName != null) {
                if (LEGACY_CONNECTION_PROVIDER_MAPPING.containsKey(providerName)) {
                    final String actualProviderName = LEGACY_CONNECTION_PROVIDER_MAPPING.get(providerName);
                    DeprecationLogger.DEPRECATION_LOGGER.connectionProviderClassDeprecated(providerName, actualProviderName);
                    providerName = actualProviderName;
                }
                LOG.instantiatingExplicitConnectionProvider(providerName);
                final Class providerClass = strategySelector.selectStrategyImplementor(ConnectionProvider.class, providerName);
                try {
                    return instantiateExplicitConnectionProvider(providerClass);
                } catch (Exception e) {
                    throw new HibernateException("Could not instantiate connection provider [" + providerName + "]", e);
                }
            }
        }
    }
    if (configurationValues.get(AvailableSettings.DATASOURCE) != null) {
        return new DatasourceConnectionProviderImpl();
    }
    ConnectionProvider connectionProvider = null;
    final Class<? extends ConnectionProvider> singleRegisteredProvider = getSingleRegisteredProvider(strategySelector);
    if (singleRegisteredProvider != null) {
        try {
            connectionProvider = singleRegisteredProvider.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            throw new HibernateException("Could not instantiate singular-registered ConnectionProvider", e);
        }
    }
    if (connectionProvider == null) {
        if (c3p0ConfigDefined(configurationValues)) {
            connectionProvider = instantiateC3p0Provider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (proxoolConfigDefined(configurationValues)) {
            connectionProvider = instantiateProxoolProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (hikariConfigDefined(configurationValues)) {
            connectionProvider = instantiateHikariProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (viburConfigDefined(configurationValues)) {
            connectionProvider = instantiateViburProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (agroalConfigDefined(configurationValues)) {
            connectionProvider = instantiateAgroalProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (configurationValues.get(AvailableSettings.URL) != null) {
            connectionProvider = new DriverManagerConnectionProviderImpl();
        }
    }
    if (connectionProvider == null) {
        LOG.noAppropriateConnectionProvider();
        connectionProvider = new UserSuppliedConnectionProviderImpl();
    }
    final Map injectionData = (Map) configurationValues.get(INJECTION_DATA);
    if (injectionData != null && injectionData.size() > 0) {
        final ConnectionProvider theConnectionProvider = connectionProvider;
        new BeanInfoHelper(connectionProvider.getClass()).applyToBeanInfo(connectionProvider, new BeanInfoHelper.BeanInfoDelegate() {

            public void processBeanInfo(BeanInfo beanInfo) throws Exception {
                final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor descriptor : descriptors) {
                    final String propertyName = descriptor.getName();
                    if (injectionData.containsKey(propertyName)) {
                        final Method method = descriptor.getWriteMethod();
                        method.invoke(theConnectionProvider, injectionData.get(propertyName));
                    }
                }
            }
        });
    }
    return connectionProvider;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) HibernateException(org.hibernate.HibernateException) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) StrategySelector(org.hibernate.boot.registry.selector.spi.StrategySelector) HibernateException(org.hibernate.HibernateException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) MultiTenancyStrategy(org.hibernate.MultiTenancyStrategy) BeanInfoHelper(org.hibernate.internal.util.beans.BeanInfoHelper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 53 with BeanInfo

use of java.beans.BeanInfo in project cytoscape-impl by cytoscape.

the class FilterIO method getParameters.

public static Map<String, Object> getParameters(Transformer<?, ?> transformer) throws IntrospectionException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Class<?> type = transformer.getClass();
    BeanInfo info = Introspector.getBeanInfo(type);
    for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
        Method method = descriptor.getReadMethod();
        if (method.isAnnotationPresent(Tunable.class)) {
            try {
                map.put(descriptor.getName(), method.invoke(transformer));
            } catch (IllegalArgumentException e) {
                logger.error("Unexpected error", e);
            } catch (IllegalAccessException e) {
                logger.error("Unexpected error", e);
            } catch (InvocationTargetException e) {
                logger.error("Unexpected error", e);
            }
        }
    }
    for (Field field : type.getFields()) {
        if (field.isAnnotationPresent(Tunable.class)) {
            try {
                map.put(field.getName(), field.get(transformer));
            } catch (IllegalArgumentException e) {
                logger.error("Unexpected error", e);
            } catch (IllegalAccessException e) {
                logger.error("Unexpected error", e);
            }
        }
    }
    return map;
}
Also used : Field(java.lang.reflect.Field) PropertyDescriptor(java.beans.PropertyDescriptor) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 54 with BeanInfo

use of java.beans.BeanInfo in project cytoscape-impl by cytoscape.

the class FilterIO method getProperties.

private static Map<String, PropertyInfo> getProperties(Transformer<?, ?> transformer) {
    Map<String, PropertyInfo> properties = new HashMap<String, PropertyInfo>();
    Class<?> type = transformer.getClass();
    try {
        BeanInfo info = Introspector.getBeanInfo(type);
        for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
            Method getter = descriptor.getReadMethod();
            Method setter = descriptor.getWriteMethod();
            if (getter == null || !getter.isAnnotationPresent(Tunable.class) || setter == null) {
                continue;
            }
            properties.put(descriptor.getName(), new PropertyInfo(descriptor.getPropertyType(), getter, setter, null));
        }
    } catch (IntrospectionException e) {
        logger.error("Unexpected error", e);
    }
    for (Field field : type.getFields()) {
        if (!field.isAnnotationPresent(Tunable.class)) {
            continue;
        }
        properties.put(field.getName(), new PropertyInfo(field.getType(), null, null, field));
    }
    return properties;
}
Also used : Field(java.lang.reflect.Field) PropertyDescriptor(java.beans.PropertyDescriptor) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) Tunable(org.cytoscape.work.Tunable) Method(java.lang.reflect.Method)

Example 55 with BeanInfo

use of java.beans.BeanInfo in project jSqlBox by drinkjava2.

the class InlineQueryRunner method inline.

/**
 * Usually used to translate a Bean to "field1,field2,...fieldx" format or
 * "field1=?,field2=?.... fieldx=?" format inLineSQL String piece, and save bean
 * property parameters in ThreadLocal
 *
 * @param bean
 *            The Bean will be transfer to SQL piece
 * @param conditionStr
 *            The condition String
 * @param separatorStr
 *            The separator String
 * @return a SQL piece and store all bean properties as parameters in
 *         ThreadLocaled
 */
public static String inline(Object bean, String conditionStr, String separatorStr) {
    DbProRuntimeException.assertNotNull(bean, "DbProBeanUtils bean can not be null");
    Class<?> beanClass = bean.getClass();
    BeanInfo beanInfo = null;
    PropertyDescriptor[] pds = null;
    try {
        beanInfo = Introspector.getBeanInfo(beanClass);
        pds = beanInfo.getPropertyDescriptors();
    } catch (Exception e) {
        throw new DbProRuntimeException("DbProBeanUtils  fail to get bean Properties.", e);
    }
    if (pds == null || pds.length < 1)
        return "";
    StringBuilder sb = new StringBuilder();
    Object[] params = new Object[pds.length - 1];
    int i = 0;
    for (PropertyDescriptor pd : pds) {
        String fieldName = pd.getName();
        if (!"class".equals(fieldName)) {
            Method md = pd.getReadMethod();
            try {
                Object value = md.invoke(bean);
                sb.append(fieldName).append(conditionStr).append(separatorStr);
                params[i++] = value;
            } catch (Exception e) {
                throw new DbProRuntimeException("DbProBeanUtils fail to get bean Properties.", e);
            }
        }
    }
    sb.setLength(sb.length() - separatorStr.length());
    for (Object param : params) {
        DbPro.param(param);
    }
    return sb.toString();
}
Also used : DbProRuntimeException(com.github.drinkjava2.jdbpro.DbProRuntimeException) PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) DbProRuntimeException(com.github.drinkjava2.jdbpro.DbProRuntimeException) SQLException(java.sql.SQLException)

Aggregations

BeanInfo (java.beans.BeanInfo)420 PropertyDescriptor (java.beans.PropertyDescriptor)328 Method (java.lang.reflect.Method)217 SimpleBeanInfo (java.beans.SimpleBeanInfo)167 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)161 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)148 IntrospectionException (java.beans.IntrospectionException)115 InvocationTargetException (java.lang.reflect.InvocationTargetException)38 HashMap (java.util.HashMap)33 Test (org.junit.jupiter.api.Test)33 ArrayList (java.util.ArrayList)30 Field (java.lang.reflect.Field)17 Map (java.util.Map)17 Test (org.junit.Test)13 EventSetDescriptor (java.beans.EventSetDescriptor)12 MethodDescriptor (java.beans.MethodDescriptor)12 List (java.util.List)11 BeanDescriptor (java.beans.BeanDescriptor)10 HashSet (java.util.HashSet)8 Introspector (java.beans.Introspector)7