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:com.datatorrent.stram.StringCodecs.java

public static void check() {
    if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) {
        loadDefaultConverters();/*from w ww.  j  a v a 2 s.  co m*/
        for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
            try {
                final StringCodec<?> codecInstance = entry.getValue().newInstance();
                ConvertUtils.register(new Converter() {
                    @Override
                    public Object convert(Class type, Object value) {
                        return value == null ? null : codecInstance.fromString(value.toString());
                    }

                }, entry.getKey());
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:applica._APPNAME_.api.configuration.ApplicationInitializer.java

public void init() {
    if (revisionService != null)
        revisionService.disableRevisionForCurrentThread();

    LicenseManager.instance().setUser(options.get("applica.framework.licensing.user"));
    LicenseManager.instance().mustBeValid();

    setupRoles();/* ww w  .  j  ava 2s.co  m*/
    setupPermissions();
    initializeCustomPermissions();

    User user = usersRepository.find(Query.build().eq(Filters.USER_MAIL, "admin@applica.guru")).findFirst()
            .orElse(null);
    if (user == null) {
        user = new User();
        String encodedPassword = new Md5PasswordEncoder().encodePassword("applica", null);
        user.setMail("admin@applica.guru");
        user.setPassword(encodedPassword);
        user.setName("admin");
        user.setActive(true);
        usersRepository.save(user);
    }

    Role role = rolesRepository.find(Query.build().filter(Filters.ROLE_NAME, Role.ADMIN)).findFirst()
            .orElse(null);

    if (role != null) {
        user.setRoles(new ArrayList<>());
        user.getRoles().add(role);
        usersRepository.save(user);
    }

    NullableDateConverter dateConverter = new NullableDateConverter();
    dateConverter.setPatterns(new String[] { "dd/MM/yyyy HH:mm", "MM/dd/yyyy HH:mm", "yyyy-MM-dd HH:mm",
            "dd/MM/yyyy", "MM/dd/yyyy", "yyyy-MM-dd", "HH:mm" });
    ConvertUtils.register(dateConverter, Date.class);

    logger.info("Applica Framework app started");
    if (revisionService != null)
        revisionService.enableRevisionForCurrentThread();

}

From source file:commonSession.PersistAttivitaFacadeBean.java

/**
 * /*from  w  w w.j a  v  a  2 s  . c  o  m*/
 */
public PersistAttivitaFacadeBean() {
    super();
    conf.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor());
    conf.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
    conf.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor());
    conf.registerJsonValueProcessor(Time.class, new TimeJsonValueProcessor());

    ConvertUtils.register(new DateLocaleConverterCustom(Locale.ITALY, "dd.MM.yyyy"), Date.class);
    ConvertUtils.register(new DoubleLocalConverterCustom(Locale.ITALY), Double.class);
    ConvertUtils.register(new IntegerLocalConverterCustom(Locale.ITALY), Integer.class);
}

From source file:com.datatorrent.stram.StringCodecs.java

public static <T> void register(final Class<? extends StringCodec<?>> codec, final Class<T> clazz)
        throws InstantiationException, IllegalAccessException {
    check();//  w  w  w .j a va  2s.  c o m
    final StringCodec<?> codecInstance = codec.newInstance();
    ConvertUtils.register(new Converter() {
        @Override
        public Object convert(Class type, Object value) {
            return value == null ? null : codecInstance.fromString(value.toString());
        }

    }, clazz);
    codecs.put(clazz, codec);
}

From source file:net.servicefixture.converter.ObjectConverter.java

public static void register(final net.servicefixture.converter.Converter converter, Class clazz) {
    ConvertUtils.register(new Converter() {
        public Object convert(Class type, Object obj) {
            return converter.fromObject(obj);
        }/*from  w w  w.java 2s .  co  m*/

    }, clazz);

    converters.put(clazz, converter);
}

From source file:com.datatorrent.contrib.parser.RegexParser.java

@Override
public void processTuple(byte[] tuple) {
    if (tuple == null) {
        if (err.isConnected()) {
            err.emit(new KeyValPair<String, String>(null, "Blank/null tuple"));
        }/*from w w  w . ja  v  a  2 s .  c  o  m*/
        errorTupleCount++;
        return;
    }
    String incomingString = new String(tuple);
    if (StringUtils.isBlank(incomingString)) {
        if (err.isConnected()) {
            err.emit(new KeyValPair<String, String>(incomingString, "Blank tuple"));
        }
        errorTupleCount++;
        return;
    }
    try {
        if (out.isConnected() && clazz != null) {
            Matcher matcher = pattern.matcher(incomingString);
            boolean patternMatched = false;
            Constructor<?> ctor = clazz.getConstructor();
            Object object = ctor.newInstance();

            if (matcher.find()) {
                for (int i = 0; i <= matcher.groupCount() - 1; i++) {
                    if (delimitedParserSchema.getFields().get(i).getType() == DelimitedSchema.FieldType.DATE) {
                        DateTimeConverter dtConverter = new DateConverter();
                        dtConverter.setPattern((String) delimitedParserSchema.getFields().get(i)
                                .getConstraints().get(DelimitedSchema.DATE_FORMAT));
                        ConvertUtils.register(dtConverter, Date.class);
                    }
                    BeanUtils.setProperty(object, delimitedParserSchema.getFields().get(i).getName(),
                            matcher.group(i + 1));
                }
                patternMatched = true;
            }
            if (!patternMatched) {
                throw new ConversionException(
                        "The incoming tuple do not match with the Regex pattern defined.");
            }

            out.emit(object);
            emittedObjectCount++;
        }

    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | InstantiationException
            | ConversionException e) {
        if (err.isConnected()) {
            err.emit(new KeyValPair<String, String>(incomingString, e.getMessage()));
            logger.debug("Regex Expression : {} Incoming tuple : {}", splitRegexPattern, incomingString);
        }
        errorTupleCount++;
        logger.error("Tuple could not be parsed. Reason {}", e.getMessage());
    }
}

From source file:com.agnie.useradmin.tools.dbinit.DBInit.java

@Override
public void process() throws Exception {
    Properties initProperties = readInitProperties();
    System.out.println("DB is getting Initalized ....");
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override/*from w  ww.j av  a  2s.  com*/
        protected void configure() {
            Properties props = new Properties();
            if (host != null && !host.isEmpty())
                props.put("javax.persistence.jdbc.url", "jdbc:mysql://" + host
                        + (port != null && !port.isEmpty() ? ":" + port : "") + "/UserAdmin");
            if (username != null && !username.isEmpty()) {
                props.put("javax.persistence.jdbc.user", username);
                props.put("javax.persistence.jdbc.password", password);
            }
            props.put("eclipselink.ddl-generation", "drop-and-create-tables");
            install(new JpaPersistModule("user-admin").properties(props));
            bind(PersistenceLifeCycleManager.class).annotatedWith(UserAdminPersistService.class)
                    .to(UserAdminPersistenceLifeCycleManager.class);
            bind(DBInitUserAdminPersistenceInitilizer.class).asEagerSingleton();
        }
    });
    AuthLevelConvert converter = new AuthLevelConvert();
    ConvertUtils.register(converter, AuthLevel.class);
    DBInitializer init = injector.getInstance(DBInitializer.class);
    init.setInitProperties(initProperties);
    PersistenceLifeCycleManager uamanager = injector
            .getInstance(Key.get(PersistenceLifeCycleManager.class, UserAdminPersistService.class));
    uamanager.beginUnitOfWork();
    init.IntializeData();
    uamanager.endUnitOfWork();

    System.out.println("DB got Initalized succesfully....");
}

From source file:com.xidu.framework.common.util.Utils.java

public static List<?> convertDomainListToDtoList(List<?> origDomainList, Class<?> dtoClass) {
    if (null == origDomainList) {
        return null;
    }/*w ww. j  av a  2 s. c  om*/
    List<Object> convertedList = new ArrayList<Object>();
    for (Object orig : origDomainList) {
        Object dest;
        try {
            dest = dtoClass.newInstance();
            ConvertUtils.register(new DateConverter(null), Date.class);
            BeanUtils.copyProperties(dest, orig);
            convertedList.add(dest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return convertedList;
}

From source file:com.xidu.framework.common.util.Utils.java

public static List<?> convertDtoListToDomainList(List<?> origDtoList, Class<?> domainClass) {
    if (null == origDtoList) {
        return null;
    }//from w w w . j av a  2  s.  c  o m
    List<Object> convertedList = new ArrayList<Object>();
    for (Object orig : origDtoList) {
        Object dest;
        try {
            dest = domainClass.newInstance();
            ConvertUtils.register(new DateConverter(null), Date.class);
            BeanUtils.copyProperties(dest, orig);
            convertedList.add(dest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return convertedList;
}

From source file:com.lingxiang2014.ExcelView.java

public void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Assert.notEmpty(properties);/*from w ww  .j av  a2 s .c o  m*/
    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);
                    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");
    }
}