Search in sources :

Example 91 with PropertyDescriptor

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

the class JSONWriter method bean.

private void bean(Object object) {
    add("{");
    BeanInfo info;
    boolean addedSomething = false;
    try {
        info = Introspector.getBeanInfo(object.getClass());
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            String name = prop.getName();
            Method accessor = prop.getReadMethod();
            if ((emitClassName || !"class".equals(name)) && accessor != null) {
                if (!accessor.isAccessible())
                    accessor.setAccessible(true);
                Object value = accessor.invoke(object, (Object[]) null);
                if (value == null)
                    continue;
                if (addedSomething)
                    add(',');
                add(name, value);
                addedSomething = true;
            }
        }
        Field[] ff = object.getClass().getFields();
        for (int i = 0; i < ff.length; ++i) {
            Field field = ff[i];
            Object value = field.get(object);
            if (value == null)
                continue;
            if (addedSomething)
                add(',');
            add(field.getName(), value);
            addedSomething = true;
        }
    } catch (IllegalAccessException iae) {
        iae.printStackTrace();
    } catch (InvocationTargetException ite) {
        ite.getCause().printStackTrace();
        ite.printStackTrace();
    } catch (IntrospectionException ie) {
        ie.printStackTrace();
    }
    add("}");
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ApiField(com.alipay.api.internal.mapping.ApiField) Field(java.lang.reflect.Field) ApiListField(com.alipay.api.internal.mapping.ApiListField)

Example 92 with PropertyDescriptor

use of java.beans.PropertyDescriptor 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 93 with PropertyDescriptor

use of java.beans.PropertyDescriptor 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 94 with PropertyDescriptor

use of java.beans.PropertyDescriptor 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 95 with PropertyDescriptor

use of java.beans.PropertyDescriptor 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)

Aggregations

PropertyDescriptor (java.beans.PropertyDescriptor)836 Method (java.lang.reflect.Method)396 BeanInfo (java.beans.BeanInfo)339 IntrospectionException (java.beans.IntrospectionException)188 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)171 SimpleBeanInfo (java.beans.SimpleBeanInfo)142 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)141 InvocationTargetException (java.lang.reflect.InvocationTargetException)108 ArrayList (java.util.ArrayList)90 HashMap (java.util.HashMap)66 Field (java.lang.reflect.Field)59 Map (java.util.Map)52 Test (org.junit.Test)39 IOException (java.io.IOException)34 MockJavaBean (org.apache.harmony.beans.tests.support.mock.MockJavaBean)34 List (java.util.List)33 HashSet (java.util.HashSet)21 Type (java.lang.reflect.Type)20 Set (java.util.Set)20 LinkedHashMap (java.util.LinkedHashMap)19