Search in sources :

Example 96 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project jdbi by jdbi.

the class BeanMapper method specialize0.

private RowMapper<T> specialize0(ResultSet rs, StatementContext ctx, List<String> columnNames, List<ColumnNameMatcher> columnNameMatchers, List<String> unmatchedColumns) throws SQLException {
    final List<RowMapper<?>> mappers = new ArrayList<>();
    final List<PropertyDescriptor> properties = new ArrayList<>();
    for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
        Nested anno = Stream.of(descriptor.getReadMethod(), descriptor.getWriteMethod()).filter(Objects::nonNull).map(m -> m.getAnnotation(Nested.class)).filter(Objects::nonNull).findFirst().orElse(null);
        if (anno == null) {
            String paramName = prefix + paramName(descriptor);
            findColumnIndex(paramName, columnNames, columnNameMatchers, () -> debugName(descriptor)).ifPresent(index -> {
                Type type = descriptor.getReadMethod().getGenericReturnType();
                ColumnMapper<?> mapper = ctx.findColumnMapperFor(type).orElse((r, n, c) -> r.getObject(n));
                mappers.add(new SingleColumnMapper<>(mapper, index + 1));
                properties.add(descriptor);
                unmatchedColumns.remove(columnNames.get(index));
            });
        } else {
            String nestedPrefix = prefix + anno.value();
            RowMapper<?> nestedMapper = nestedMappers.computeIfAbsent(descriptor, d -> new BeanMapper<>(d.getPropertyType(), nestedPrefix)).specialize0(rs, ctx, columnNames, columnNameMatchers, unmatchedColumns);
            mappers.add(nestedMapper);
            properties.add(descriptor);
        }
    }
    if (mappers.isEmpty() && columnNames.size() > 0) {
        throw new IllegalArgumentException(String.format("Mapping bean type %s " + "didn't find any matching columns in result set", type));
    }
    return (r, c) -> {
        T bean = construct();
        for (int i = 0; i < mappers.size(); i++) {
            RowMapper<?> mapper = mappers.get(i);
            PropertyDescriptor property = properties.get(i);
            Object value = mapper.map(r, ctx);
            writeProperty(bean, property, value);
        }
        return bean;
    };
}
Also used : ReflectionMapperUtil.getColumnNames(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.getColumnNames) RowMapperFactory(org.jdbi.v3.core.mapper.RowMapperFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Nested(org.jdbi.v3.core.mapper.Nested) SingleColumnMapper(org.jdbi.v3.core.mapper.SingleColumnMapper) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayList(java.util.ArrayList) StatementContext(org.jdbi.v3.core.statement.StatementContext) Objects(java.util.Objects) Introspector(java.beans.Introspector) SQLException(java.sql.SQLException) List(java.util.List) Stream(java.util.stream.Stream) Type(java.lang.reflect.Type) PropertyDescriptor(java.beans.PropertyDescriptor) ResultSet(java.sql.ResultSet) BeanInfo(java.beans.BeanInfo) Map(java.util.Map) ReflectionMapperUtil.findColumnIndex(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.findColumnIndex) ColumnMapper(org.jdbi.v3.core.mapper.ColumnMapper) RowMapper(org.jdbi.v3.core.mapper.RowMapper) PropertyDescriptor(java.beans.PropertyDescriptor) ArrayList(java.util.ArrayList) Nested(org.jdbi.v3.core.mapper.Nested) Type(java.lang.reflect.Type) Objects(java.util.Objects) RowMapper(org.jdbi.v3.core.mapper.RowMapper)

Example 97 with PropertyDescriptor

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

Example 98 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project jeesuite-libs by vakinge.

the class ExcelBeanHelper method doCacheClass.

/**
 * @param clazz
 * @param canonicalName
 * @return
 * @throws IntrospectionException
 */
private static synchronized void doCacheClass(Class<?> clazz, String canonicalName) throws Exception {
    if (aliasPropertyDescriptorCache.containsKey(canonicalName))
        return;
    Map<String, PropertyDescriptor> map = new HashMap<>();
    Map<String, PropertyDescriptor> aliasMap = new HashMap<>();
    List<TitleMeta> titleMetas = new ArrayList<>();
    BeanInfo srcBeanInfo = Introspector.getBeanInfo(clazz);
    PropertyDescriptor[] descriptors = srcBeanInfo.getPropertyDescriptors();
    Map<String, TitleMeta> parentMap = new HashMap<>();
    int maxRow = 1;
    for (PropertyDescriptor descriptor : descriptors) {
        String name = descriptor.getName();
        if ("class".equals(name))
            continue;
        Method readMethod = descriptor.getReadMethod();
        Method writeMethod = descriptor.getWriteMethod();
        if (readMethod == null)
            try {
                readMethod = clazz.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
                descriptor.setReadMethod(readMethod);
            } catch (NoSuchMethodException | SecurityException e) {
            }
        if (writeMethod == null)
            try {
                writeMethod = clazz.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), descriptor.getPropertyType());
                descriptor.setWriteMethod(writeMethod);
            } catch (NoSuchMethodException | SecurityException e) {
            }
        if (readMethod != null || writeMethod != null) {
            map.put(descriptor.getName(), descriptor);
            // 
            TitleCell annotation = null;
            try {
                annotation = clazz.getDeclaredField(name).getAnnotation(TitleCell.class);
            } catch (NoSuchFieldException e) {
                annotation = clazz.getSuperclass().getDeclaredField(name).getAnnotation(TitleCell.class);
            }
            if (annotation != null) {
                aliasMap.put(annotation.name().trim(), descriptor);
                TitleMeta cell = new TitleMeta(annotation.name());
                cell.setValueType(annotation.type());
                if (StringUtils.isBlank(annotation.parentName())) {
                    cell.setColumnIndex(annotation.column());
                    cell.setRowIndex(annotation.row());
                    titleMetas.add(cell);
                } else {
                    TitleMeta cellParent = parentMap.get(annotation.parentName());
                    if (cellParent == null) {
                        cellParent = new TitleMeta(annotation.parentName());
                        cellParent.setValueType(annotation.type());
                        cellParent.setColumnIndex(annotation.column());
                        parentMap.put(annotation.parentName(), cellParent);
                        titleMetas.add(cellParent);
                    }
                    cell.setColumnIndex(annotation.column());
                    cell.setRowIndex(annotation.row());
                    cellParent.addChildren(cell);
                    maxRow = annotation.row() > maxRow ? annotation.row() : maxRow;
                }
            }
        }
    }
    ExcelMeta excelMeta = new ExcelMeta(clazz, titleMetas, maxRow);
    titleCellBeanCache.put(canonicalName, excelMeta);
    aliasPropertyDescriptorCache.put(canonicalName, aliasMap);
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) TitleCell(com.jeesuite.common2.excel.annotation.TitleCell) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ExcelMeta(com.jeesuite.common2.excel.model.ExcelMeta) TitleMeta(com.jeesuite.common2.excel.model.TitleMeta)

Example 99 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project jeesuite-libs by vakinge.

the class ExcelBeanHelper method beanToExcelValueArrays.

public static <T> List<Object[]> beanToExcelValueArrays(List<T> datas, Class<T> clazz) {
    Map<String, PropertyDescriptor> pds = getAliasPropertyDescriptors(clazz);
    List<Object[]> result = new ArrayList<>(datas.size() + 1);
    String[] titles = getExcelMeta(clazz).getFinalTitles();
    if (datas == null || datas.isEmpty())
        return result;
    int valNums = titles.length;
    Object[] valArrs;
    for (T e : datas) {
        valArrs = new Object[valNums];
        try {
            for (int i = 0; i < titles.length; i++) {
                PropertyDescriptor descriptor = pds.get(titles[i]);
                if (descriptor != null) {
                    valArrs[i] = descriptor.getReadMethod().invoke(e);
                }
            }
            result.add(valArrs);
        } catch (Exception e2) {
            throw new BeanConverterException(e2);
        }
    }
    return result;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) ArrayList(java.util.ArrayList) ExcelOperBaseException(com.jeesuite.common2.excel.ExcelOperBaseException) IntrospectionException(java.beans.IntrospectionException)

Example 100 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project jeesuite-libs by vakinge.

the class ExcelBeanHelper method setRowValues.

public static <T> List<T> setRowValues(Class<T> clazz, List<String> contents) {
    try {
        Map<String, PropertyDescriptor> pds = getAliasPropertyDescriptors(clazz);
        List<T> results = new ArrayList<>();
        if (contents.isEmpty())
            return results;
        String[] titles = getExcelMeta(clazz).getFinalTitles();
        int titleRowCount = getExcelMeta(clazz).getTitleRowNum();
        // 解析内容标题内容为数组
        List<String> contentTitles = new ArrayList<>();
        // 第一行为sheet信息
        for (int i = 1; i <= titleRowCount; i++) {
            contentTitles.addAll(Arrays.asList(contents.get(i).split(ExcelValidator.FIELD_SPLIT)));
        }
        for (int i = 0; i < titles.length; i++) {
            if (titleRowCount == 1) {
                if (!StringUtils.equals(titles[i], contentTitles.get(i)))
                    throw new ExcelOperBaseException("格式错误,没有找到列[" + titles[i] + "]");
            } else {
                if (!contentTitles.contains(titles[i]))
                    throw new ExcelOperBaseException("格式错误,没有找到列[" + titles[i] + "]");
            }
        }
        String[] vals = null;
        for (int i = titleRowCount + 1; i < contents.size(); i++) {
            String line = contents.get(i);
            if (line.startsWith(ExcelValidator.SHEET_NAME_PREFIX)) {
                throw new ExcelOperBaseException("模板错误(暂不支持多个sheet)");
            }
            T instance = clazz.newInstance();
            vals = line.split(ExcelValidator.FIELD_SPLIT);
            boolean anyColumnNotEmpty = false;
            inner: for (int j = 0; j < titles.length; j++) {
                if (vals.length < j + 1)
                    break inner;
                anyColumnNotEmpty = anyColumnNotEmpty || StringUtils.isNotBlank(vals[j]);
                PropertyDescriptor propertyDescriptor = pds.get(clearWrapper(titles[j]).trim());
                if (propertyDescriptor != null && vals[j] != null) {
                    try {
                        Object rawValue = rawValue(vals[j], propertyDescriptor.getPropertyType());
                        propertyDescriptor.getWriteMethod().invoke(instance, rawValue);
                    } catch (Exception e) {
                    // TODO: handle exception
                    }
                }
            }
            if (anyColumnNotEmpty) {
                results.add(instance);
            }
        }
        return results;
    } catch (Exception e) {
        if (e instanceof ExcelOperBaseException)
            throw (ExcelOperBaseException) e;
        throw new BeanConverterException(e);
    }
}
Also used : ExcelOperBaseException(com.jeesuite.common2.excel.ExcelOperBaseException) PropertyDescriptor(java.beans.PropertyDescriptor) ArrayList(java.util.ArrayList) ExcelOperBaseException(com.jeesuite.common2.excel.ExcelOperBaseException) IntrospectionException(java.beans.IntrospectionException)

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