Example usage for org.apache.commons.beanutils ConvertUtils register

List of usage examples for org.apache.commons.beanutils ConvertUtils register

Introduction

In this page you can find the example usage for org.apache.commons.beanutils ConvertUtils register.

Prototype

public static void register(Converter converter, Class clazz) 

Source Link

Document

Register a custom Converter for the specified destination Class, replacing any previously registered Converter.

For more details see ConvertUtilsBean.

Usage

From source file:ReflectionUtils.java

/**
 * clazzproperty./*from   w ww.j a  va  2s.c  om*/
 * 
 * @param value
 *            
 * @param clazz
 *            Class
 * @param propertyName
 *            Class.
 */
public static Object convertValue(Object value, Class<?> toType) {
    try {
        DateConverter dc = new DateConverter();
        dc.setUseLocaleFormat(true);
        dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
        ConvertUtils.register(dc, Date.class);
        return ConvertUtils.convert(value, toType);
    } catch (Exception e) {
        throw convertToUncheckedException(e);
    }
}

From source file:com.feilong.commons.core.bean.BeanUtilTest.java

/**
 * Copy properties./* w  w  w .  j a  va 2  s. c o  m*/
 */
@Test
public void copyProperties() {
    User a = new User();
    a.setId(5L);
    a.setDate(new Date());
    String[] nickName = { "feilong", "", "venusdrogon" };
    a.setNickName(nickName);

    User b = new User();

    String[] aStrings = { "date", "id", "nickName" };
    ConvertUtils.register(new DateLocaleConverter(Locale.US, DatePattern.forToString), Date.class);
    BeanUtil.copyProperties(b, a, aStrings);

    if (log.isDebugEnabled()) {
        log.debug(JsonUtil.format(b));
    }

}

From source file:com.dp2345.ExcelView.java

/**
 * ?Excel//from w  ww  .ja  v a2  s. c o m
 * 
 * @param model
 *            ?
 * @param workbook
 *            workbook
 * @param request
 *            request
 * @param response
 *            response
 */
public void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Assert.notEmpty(properties);
    HSSFSheet sheet;
    if (StringUtils.isNotEmpty(sheetName)) {
        sheet = workbook.createSheet(sheetName);
    } else {
        sheet = workbook.createSheet();
    }
    int rowNumber = 0;
    if (titles != null && titles.length > 0) {
        HSSFRow header = sheet.createRow(rowNumber);
        header.setHeight((short) 400);
        for (int i = 0; i < properties.length; i++) {
            HSSFCell cell = header.createCell(i);
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 11);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            if (i == 0) {
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                HSSFComment comment = patriarch
                        .createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 4, 4));
                comment.setString(new HSSFRichTextString("P" + "o" + "w" + "e" + "r" + "e" + "d" + " " + "B"
                        + "y" + " " + "D" + "P" + "2" + "3" + "4" + "5"));
                cell.setCellComment(comment);
            }
            if (titles.length > i && titles[i] != null) {
                cell.setCellValue(titles[i]);
            } else {
                cell.setCellValue(properties[i]);
            }
            if (widths != null && widths.length > i && widths[i] != null) {
                sheet.setColumnWidth(i, widths[i]);
            } else {
                sheet.autoSizeColumn(i);
            }
        }
        rowNumber++;
    }
    if (data != null) {
        for (Object item : data) {
            HSSFRow row = sheet.createRow(rowNumber);
            for (int i = 0; i < properties.length; i++) {
                HSSFCell cell = row.createCell(i);
                if (converters != null && converters.length > i && converters[i] != null) {
                    Class<?> clazz = PropertyUtils.getPropertyType(item, properties[i]);
                    ConvertUtils.register(converters[i], clazz);
                    cell.setCellValue(BeanUtils.getProperty(item, properties[i]));
                    ConvertUtils.deregister(clazz);
                    if (clazz.equals(Date.class)) {
                        DateConverter dateConverter = new DateConverter();
                        dateConverter.setPattern(DEFAULT_DATE_PATTERN);
                        ConvertUtils.register(dateConverter, Date.class);
                    }
                } else {
                    cell.setCellValue(BeanUtils.getProperty(item, properties[i]));
                }
                if (rowNumber == 0 || rowNumber == 1) {
                    if (widths != null && widths.length > i && widths[i] != null) {
                        sheet.setColumnWidth(i, widths[i]);
                    } else {
                        sheet.autoSizeColumn(i);
                    }
                }
            }
            rowNumber++;
        }
    }
    if (contents != null && contents.length > 0) {
        rowNumber++;
        for (String content : contents) {
            HSSFRow row = sheet.createRow(rowNumber);
            HSSFCell cell = row.createCell(0);
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setColor(HSSFColor.GREY_50_PERCENT.index);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(content);
            rowNumber++;
        }
    }
    response.setContentType("application/force-download");
    if (StringUtils.isNotEmpty(filename)) {
        response.setHeader("Content-disposition",
                "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
    } else {
        response.setHeader("Content-disposition", "attachment");
    }
}

From source file:com.xyz.util.ReflectionUtil.java

/**
 * ?clazzproperty.//from  w  w  w. ja  va 2s  . co m
 * 
 * @param value ?
 * @param clazz ???Class
 * @param propertyName ???Class.
 */
public static Object convertValue(Object value, Class<?> toType) {
    try {
        DateConverter dc = new DateConverter();
        dc.setUseLocaleFormat(true);
        dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
        ConvertUtils.register(dc, Date.class);
        return ConvertUtils.convert(value.toString(), toType);
    } catch (Exception e) {
        throw convertToUncheckedException(e);
    }
}

From source file:com.util.poi.ExcelView.java

/**
 * ?Excel//  www .  java  2  s  .  c om
 * 
 * @param model
 *            ?
 * @param workbook
 *            workbook
 * @param request
 *            request
 * @param response
 *            response
 */
public void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Assert.notEmpty(properties);
    HSSFSheet sheet;
    if (StringUtils.isNotEmpty(sheetName)) {
        sheet = workbook.createSheet(sheetName);
    } else {
        sheet = workbook.createSheet();
    }
    int rowNumber = 0;
    if (titles != null && titles.length > 0) {
        HSSFRow header = sheet.createRow(rowNumber);
        header.setHeight((short) 400);
        for (int i = 0; i < properties.length; i++) {
            HSSFCell cell = header.createCell(i);
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 11);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            if (i == 0) {
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                HSSFComment comment = patriarch
                        .createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 4, 4));
                //comment.setString(new HSSFRichTextString("P" + "o" + "w" + "e" + "r" + "e" + "d" + " " + "B" + "y" + " " + "S" + "H" + "O" + "P" + "+" + "+"));
                cell.setCellComment(comment);
            }
            if (titles.length > i && titles[i] != null) {
                cell.setCellValue(titles[i]);
            } else {
                cell.setCellValue(properties[i]);
            }
            if (widths != null && widths.length > i && widths[i] != null) {
                sheet.setColumnWidth(i, widths[i]);
            } else {
                sheet.autoSizeColumn(i);
            }
        }
        rowNumber++;
    }
    if (data != null) {
        for (Object item : data) {
            HSSFRow row = sheet.createRow(rowNumber);
            for (int i = 0; i < properties.length; i++) {
                HSSFCell cell = row.createCell(i);
                if (converters != null && converters.length > i && converters[i] != null) {
                    Class<?> clazz = PropertyUtils.getPropertyType(item, properties[i]);
                    ConvertUtils.register(converters[i], clazz);
                    /*   Map<String, Object> map=toHashMap(item);
                       cell.setCellValue(map.get(properties[i]).toString());*/
                    cell.setCellValue(BeanUtils.getProperty(item, properties[i]));
                    ConvertUtils.deregister(clazz);
                    if (clazz.equals(Date.class)) {
                        DateConverter dateConverter = new DateConverter();
                        dateConverter.setPattern(DEFAULT_DATE_PATTERN);
                        ConvertUtils.register(dateConverter, Date.class);
                    }
                } else {
                    /*Map<String, Object> map=toHashMap(item);
                    cell.setCellValue(map.get(properties[i]).toString());*/
                    cell.setCellValue(BeanUtils.getProperty(item, properties[i]));
                }
                if (rowNumber == 0 || rowNumber == 1) {
                    if (widths != null && widths.length > i && widths[i] != null) {
                        sheet.setColumnWidth(i, widths[i]);
                    } else {
                        sheet.autoSizeColumn(i);
                    }
                }
            }
            rowNumber++;
        }
    }
    if (contents != null && contents.length > 0) {
        rowNumber++;
        for (String content : contents) {
            HSSFRow row = sheet.createRow(rowNumber);
            HSSFCell cell = row.createCell(0);
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setColor(HSSFColor.GREY_50_PERCENT.index);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(content);
            rowNumber++;
        }
    }
    response.setContentType("application/force-download");
    if (StringUtils.isNotEmpty(filename)) {
        response.setHeader("Content-disposition",
                "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
    } else {
        response.setHeader("Content-disposition", "attachment");
    }
}

From source file:com.abssh.util.ReflectionUtils.java

/**
 * ??// ww w.j  a  v  a  2  s.c  o m
 * 
 * @param value
 *            ?
 * @param toType
 *            
 */
public static Object convertValue(Object value, Class<?> toType) {
    if (value == null) {
        return null;
    }
    if (value.equals("") && toType.getName().equals("java.util.Date")) {
        return null;
    }
    try {
        DateConverter dc = new DateConverter();
        dc.setUseLocaleFormat(true);
        dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
        ConvertUtils.register(dc, Date.class);
        return ConvertUtils.convert(value, toType);
    } catch (Exception e) {
        throw convertReflectionExceptionToUnchecked(e);
    }
}

From source file:com.projity.field.FieldConverter.java

private FieldConverter() {
    instance = this;
    stringConverter = new StringConverter(false);
    compactStringConverter = new StringConverter(true);
    ConvertUtils.register(stringConverter, String.class); // Wrapper class
    ConvertUtils.register(new DateConverter(), Date.class); // Wrapper class
    ConvertUtils.register(new CalendarConverter(), GregorianCalendar.class); // Wrapper class
    ConvertUtils.register(new DurationConverter(), Duration.class); // Wrapper class
    ConvertUtils.register(new WorkConverter(), Work.class); // Wrapper class
    ConvertUtils.register(new MoneyConverter(), Money.class); // Wrapper class
    Converter longConverter = new LongConverter();
    ConvertUtils.register(longConverter, Long.TYPE); // Native type
    ConvertUtils.register(longConverter, Long.class); // Wrapper class
    Converter doubleConverter = new DoubleConverter();
    ConvertUtils.register(doubleConverter, Double.TYPE); // Native type
    ConvertUtils.register(doubleConverter, Double.class); // Wrapper class

    // short context converters
    HashMap<Class, Converter> compactMap = new HashMap<Class, Converter>();
    contextMaps.put(COMPACT_CONVERTER_CONTEXT, compactMap);
    compactMap.put(String.class, compactStringConverter);
    // no need for duration or money as parsing is done in long form

}

From source file:com.xyz.util.ReflectionUtil.java

/**
 * ?clazzproperty./*  www .ja v a 2 s  .co  m*/
 * 
 * @param value ?
 * @param clazz ???Class
 * @param propertyName ???Class.
 */
public static Object convertValue(Object value, Class<?> clazz, String propertyName) {
    try {
        Class<?> toType = BeanUtils.getPropertyDescriptor(clazz, propertyName).getPropertyType();
        DateConverter dc = new DateConverter();
        dc.setUseLocaleFormat(true);
        dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
        ConvertUtils.register(dc, Date.class);
        //String???''
        if (toType.equals(String.class))
            value = "'" + value + "'";
        return ConvertUtils.convert(value.toString(), toType);

    } catch (Exception e) {
        throw convertToUncheckedException(e);
    }
}

From source file:com.rodaxsoft.junit.mailgun.MailgunManagerTestCase.java

/**
 * Test for {@link MailgunManager#getMailingListMembers(String, Class)}
 *//*  w ww.ja  v  a  2  s  .  co m*/
@Test
public void testGetMailingListMembersWithVarsType() {

    // Register converters
    Class<MemberDetails> varsType = MemberDetails.class;
    ConvertUtils.register(new MemberDetailsConverter(), varsType);

    Object result;
    try {
        result = MailgunManager.getMailingListMembers(sMailingListAddress, varsType);
        assertTrue(result != null);

    } catch (Exception e) {
        LOG.error("Get Mailing List Members Error", e);
        fail(e.getMessage());
    }

    finally {
        // De-register converters
        ConvertUtils.deregister();
    }

}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public <T> T findOneObj(String dbName, String collName, Map queryMap, Class<T> clazz)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    DB db = mongoClient.getDB(dbName);/*from www  .ja  va2  s.  c  o  m*/
    DBCollection coll = db.getCollection(collName);
    BasicDBObject query = new BasicDBObject(queryMap);
    DBObject map = coll.findOne(query);
    if (map == null) {
        return null;
    }
    T obj = clazz.newInstance();
    ConvertUtils.register(new DateConverter(null), Date.class);
    BeanUtils.populate(obj, map.toMap());
    return obj;
}