Java Code Examples for org.apache.commons.beanutils.ConvertUtils#register()

The following examples show how to use org.apache.commons.beanutils.ConvertUtils#register() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StringCodecs.java    From Bats with Apache License 2.0 6 votes vote down vote up
public static void check()
{
  if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) {
    loadDefaultConverters();
    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);
      }
    }
  }
}
 
Example 2
Source File: Variable.java    From maven-framework-project with MIT License 6 votes vote down vote up
public Map<String, Object> getVariableMap() {
	Map<String, Object> vars = new HashMap<String, Object>();

	ConvertUtils.register(new DateConverter(), java.util.Date.class);

	if (StringUtil.isBlank(keys)) {
		return vars;
	}

	String[] arrayKey = keys.split(",");
	String[] arrayValue = values.split(",");
	String[] arrayType = types.split(",");
	for (int i = 0; i < arrayKey.length; i++) {
		String key = arrayKey[i];
		String value = arrayValue[i];
		String type = arrayType[i];

		Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue();
		Object objectValue = ConvertUtils.convert(value, targetType);
		vars.put(key, objectValue);
	}
	return vars;
}
 
Example 3
Source File: Variable.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
@JsonIgnore
public Map<String, Object> getVariableMap() {

	ConvertUtils.register(new DateConverter(), java.util.Date.class);

	if (StringUtils.isBlank(keys)) {
		return map;
	}

	String[] arrayKey = keys.split(",");
	String[] arrayValue = values.split(",");
	String[] arrayType = types.split(",");
	for (int i = 0; i < arrayKey.length; i++) {
		String key = arrayKey[i];
		String value = arrayValue[i];
		String type = arrayType[i];

		Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue();
		Object objectValue = ConvertUtils.convert(value, targetType);
		map.put(key, objectValue);
	}
	return map;
}
 
Example 4
Source File: StringCodecs.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static void check()
{
  if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) {
    loadDefaultConverters();
    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);
      }
    }
  }
}
 
Example 5
Source File: StringCodecs.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static <T> void register(final Class<? extends StringCodec<?>> codec, final Class<T> clazz) throws InstantiationException, IllegalAccessException
{
  check();
  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);
}
 
Example 6
Source File: KualiActionServlet.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * <p>Initialize other global characteristics of the controller servlet.</p>
    * Overridden to remove the ConvertUtils.deregister() command that caused problems
    * with the concurrent data dictionary load.  (KULRNE-4405)
    *
    * @exception ServletException if we cannot initialize these resources
    */
   @Override
protected void initOther() throws ServletException {

       String value = null;
       value = getServletConfig().getInitParameter("config");
       if (value != null) {
           config = value;
       }

       // Backwards compatibility for form beans of Java wrapper classes
       // Set to true for strict Struts 1.0 compatibility
       value = getServletConfig().getInitParameter("convertNull");
       if ("true".equalsIgnoreCase(value)
           || "yes".equalsIgnoreCase(value)
           || "on".equalsIgnoreCase(value)
           || "y".equalsIgnoreCase(value)
           || "1".equalsIgnoreCase(value)) {

           convertNull = true;
       }

       if (convertNull) {
           ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
           ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);
           ConvertUtils.register(new BooleanConverter(null), Boolean.class);
           ConvertUtils.register(new ByteConverter(null), Byte.class);
           ConvertUtils.register(new CharacterConverter(null), Character.class);
           ConvertUtils.register(new DoubleConverter(null), Double.class);
           ConvertUtils.register(new FloatConverter(null), Float.class);
           ConvertUtils.register(new IntegerConverter(null), Integer.class);
           ConvertUtils.register(new LongConverter(null), Long.class);
           ConvertUtils.register(new ShortConverter(null), Short.class);
       }

       // KULRICE-8176: KFS Notes/Attachments Tab Functionality for Note Text Error - Visible/Special characters, spaces, or tabs
       parameterEncoding = getServletConfig().getInitParameter("PARAMETER_ENCODING");
   }
 
Example 7
Source File: ToAliasBeanTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test read properties to alias bean1.
 */
@Test
public void testToAliasBean1(){
    ArrayConverter arrayConverter = new ArrayConverter(String[].class, new StringConverter(), 2);
    char[] allowedChars = { ':' };
    arrayConverter.setAllowedChars(allowedChars);

    ConvertUtils.register(arrayConverter, String[].class);

    DangaMemCachedConfig dangaMemCachedConfig = toAliasBean(getResourceBundle("messages.memcached"), DangaMemCachedConfig.class);
    assertThat(
                    dangaMemCachedConfig,
                    allOf(//
                                    hasProperty("serverList", arrayContaining("172.20.3-1.23:11211", "172.20.31.22:11211")),
                                    hasProperty("poolName", is("sidsock2")),
                                    hasProperty("expireTime", is(180)),
                                    hasProperty("weight", arrayContaining(2)),
                                    hasProperty("initConnection", is(10)),
                                    hasProperty("minConnection", is(5)),
                                    hasProperty("maxConnection", is(250)),
                                    hasProperty("maintSleep", is(30)),
                                    hasProperty("nagle", is(false)),
                                    hasProperty("socketTo", is(3000)),
                                    hasProperty("aliveCheck", is(false))
                    //
                    ));
}
 
Example 8
Source File: ConvertUtil.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Register standard default null.
 * 
 * @see ConvertUtilsBean#registerPrimitives(boolean) registerPrimitives(boolean throwException)
 * @see ConvertUtilsBean#registerStandard(boolean,boolean) registerStandard(boolean throwException, boolean defaultNull)
 * @see ConvertUtilsBean#registerOther(boolean) registerOther(boolean throwException)
 * @see ConvertUtilsBean#registerArrays(boolean,int) registerArrays(boolean throwException, int defaultArraySize)
 * @see ConvertUtilsBean#deregister(Class) ConvertUtilsBean.deregister(Class)
 * @since 1.11.2
 */
public static void registerStandardDefaultNull(){
    ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
    ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);
    ConvertUtils.register(new BooleanConverter(null), Boolean.class);
    ConvertUtils.register(new ByteConverter(null), Byte.class);
    ConvertUtils.register(new CharacterConverter(null), Character.class);
    ConvertUtils.register(new DoubleConverter(null), Double.class);
    ConvertUtils.register(new FloatConverter(null), Float.class);
    ConvertUtils.register(new IntegerConverter(null), Integer.class);
    ConvertUtils.register(new LongConverter(null), Long.class);
    ConvertUtils.register(new ShortConverter(null), Short.class);
    ConvertUtils.register(new StringConverter(null), String.class);
}
 
Example 9
Source File: BeanUtils.java    From ogham with Apache License 2.0 5 votes vote down vote up
/**
 * Register the following converters:
 * <ul>
 * <li>{@link EmailAddressConverter}</li>
 * <li>{@link SmsSenderConverter}</li>
 * </ul>
 * 
 * If a conversion error occurs it throws an exception.
 */
public static void registerDefaultConverters() {
	// TODO: auto-detect converters in the classpath ?
	// Add converter for being able to convert string address into
	// EmailAddress
	ConvertUtils.register(new EmailAddressConverter(), EmailAddress.class);
	// Add converter for being able to convert string into
	// SMS sender
	ConvertUtils.register(new SmsSenderConverter(), Sender.class);
	BeanUtilsBean.getInstance().getConvertUtils().register(true, false, 0);
}
 
Example 10
Source File: StringCodecs.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public static <T> void register(final Class<? extends StringCodec<?>> codec, final Class<T> clazz) throws InstantiationException, IllegalAccessException
{
  check();
  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);
}
 
Example 11
Source File: MyBeanUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * map to bean
 * 转换过程中,由于属性的类型不同,需要分别转换。
 * java 反射机制,转换过程中属性的类型默认都是 String 类型,否则会抛出异常,而 BeanUtils 项目,做了大量转换工作,比 java 反射机制好用
 * BeanUtils 的 populate 方法,对 Date 属性转换,支持不好,需要自己编写转换器
 *
 * @param map  待转换的 map
 * @param bean 满足 bean 格式,且需要有无参的构造方法; bean 属性的名字应该和 map 的 key 相同
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException {

    //注册几个转换器
    ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
    ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
    //注册一个类型转换器  解决 common-beanutils 为 Date 类型赋值问题
    ConvertUtils.register(new Converter() {
        //  @Override
        public Object convert(Class type, Object value) { // type : 目前所遇到的数据类型。  value :目前参数的值。
            // System.out.println(String.format("value = %s", value));

            if (value == null || value.equals("") || value.equals("null"))
                return null;
            Date date = null;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = dateFormat.parse((String) value);
            } catch (Exception e) {

                e.printStackTrace();
            }

            return date;
        }

    }, Date.class);

    BeanUtils.populate(bean, map);
}
 
Example 12
Source File: ObjectMapper.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔
 */
public static void registerDateConverter(String patterns) {
	DateConverter dc = new DateConverter();
	dc.setUseLocaleFormat(true);
	dc.setPatterns(StringUtils.split(patterns, ","));
	ConvertUtils.register(dc, Date.class);
}
 
Example 13
Source File: RegexParser.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public void processTuple(byte[] tuple)
{
  if (tuple == null) {
    if (err.isConnected()) {
      err.emit(new KeyValPair<String, String>(null, "Blank/null tuple"));
    }
    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());
  }
}
 
Example 14
Source File: Application.java    From xiaoyaoji with GNU General Public License v3.0 4 votes vote down vote up
/**
 * beanutils 日期格式化
 */
private static void initializeBeanUtilsConfig(){
    DateConverter converter = new DateConverter();
    converter.setPattern("yyyy-MM-dd HH:mm:ss");
    ConvertUtils.register(converter, Date.class);
}
 
Example 15
Source File: MailingImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Object clone(ApplicationContext con) {
	Mailing tmpMailing = (Mailing) con.getBean("Mailing");
	MailingComponent compNew = null;
	TrackableLink linkNew = null;
	DynamicTag tagNew = null;
	DynamicTagContent contentNew = null;

	try {
		ConvertUtils.register(new DateConverter(null), Date.class);
		// copy components
		for (MailingComponent compOrg : components.values()) {
			compNew = (MailingComponent) con.getBean("MailingComponent");
			BeanUtils.copyProperties(compNew, compOrg);
			if (compOrg.getBinaryBlock() != null) {
				compNew.setBinaryBlock(compOrg.getBinaryBlock(), compOrg.getMimeType());
			} else {
				compNew.setEmmBlock(compOrg.getEmmBlock(), compOrg.getMimeType());
			}
			compNew.setId(0);
			compNew.setMailingID(0);
			tmpMailing.addComponent(compNew);
		}

		// copy dyntags
		for (DynamicTag tagOrg : dynTags.values()) {
			tagNew = (DynamicTag) con.getBean("DynamicTag");
			for (DynamicTagContent contentOrg : tagOrg.getDynContent().values()) {
				contentNew = (DynamicTagContent) con.getBean("DynamicTagContent");
				BeanUtils.copyProperties(contentNew, contentOrg);
				contentNew.setId(0);
				contentNew.setDynNameID(0);
				tagNew.addContent(contentNew);
			}
			tagNew.setCompanyID(tagOrg.getCompanyID());
			tagNew.setDynName(tagOrg.getDynName());
			tagNew.setDisableLinkExtension(tagOrg.isDisableLinkExtension());
			tmpMailing.addDynamicTag(tagNew);
		}

		// copy urls
		for (TrackableLink linkOrg : trackableLinks.values()) {
			linkNew = (TrackableLink) con.getBean("TrackableLink");
			BeanUtils.copyProperties(linkNew, linkOrg);
			linkNew.setId(0);
			linkNew.setMailingID(0);
			linkNew.setActionID(linkOrg.getActionID());
			tmpMailing.getTrackableLinks().put(linkNew.getFullUrl(), linkNew);
		}

		// copy active media types
		for (Entry<Integer, Mediatype> entry : mediatypes.entrySet()) {
			Mediatype mediatype = entry.getValue();
			if (mediatype.getStatus() == Mediatype.STATUS_ACTIVE) {
				Mediatype mediatypeCopy = mediatype.copy();
				tmpMailing.getMediatypes().put(entry.getKey(), mediatypeCopy);
			}
		}

		tmpMailing.setOpenActionID(openActionID);
		tmpMailing.setClickActionID(clickActionID);

		return tmpMailing;
	} catch (Exception e) {
		logger.error("could not copy", e);
		return null;
	}
}
 
Example 16
Source File: AdminAction.java    From csustRepo with MIT License 4 votes vote down vote up
public String update() {
	
	UserForm userForm=WebUtil.params2FormBean(getParameters(), UserForm.class);
	RepAdmin admin=new RepAdmin();
	
	ConvertUtils.register(new DateLocaleConverter(), Date.class);
	try {
		BeanUtils.copyProperties(admin, userForm);
	} catch (Exception e) {
		e.printStackTrace();
	}

	admin.setUsername(admin.getUsername().trim());
	RepAdmin a=adminService.findAdminByName(admin.getUsername());
	if(a!=null&&!a.getId().equals(admin.getId())){
		getContextMap().put("message", "已经存在同名用户,请换个用户名!");
		getContextMap().put("params", getParameters());
		return "edit";
	}
	
	if(admin.getPassword()!=null&&!admin.getPassword().isEmpty()){
		admin.setPassword(MD5Util.MD5(admin.getPassword()));
	}else {
		admin.setPassword(null);
	}

	int roleid=Integer.parseInt(((String[])getParameters().get("roleid"))[0]);
	
	//判断更新的管理员是否是最后的一个未锁定的超级管理员,如果是的话则不能删除
	RepRole role=roleService.get(roleid);
	RepRole originalRole=adminService.get(admin.getId()).getRepRole();
	//判断是否符合最后一个超级管理员的条件
	if(originalRole!=null&&originalRole.getName().equals("超级管理员")
			//如果是最后一个超级管理员,则判断是否进行了修改角色或锁定操作
			&&(!role.getName().equals("超级管理员")||admin.getIslock()==1)){

		int size=adminService.countUnLockSuperAdmins();
		if(size<=1){
			getContextMap().put("message", "不能对最后一个超级管理员进行锁定或者修改角色的操作!");
			getContextMap().put("returnUrl", getRequest().getContextPath()+"/admin/user/admin_list.do");
			return "faild";
		}
	}
	
	admin.setRepRole(role);
	
	adminService.updateNotNullField(admin);
	getContextMap().put("message", "修改成功");
	getContextMap().put("returnUrl", "admin_list.do");
	
	return SUCCESS;
}
 
Example 17
Source File: StartedEventListener.java    From youkefu with Apache License 2.0 4 votes vote down vote up
@Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
  	ConvertUtils.register(new DateConverter(null), java.util.Date.class);
  	if(UKDataContext.getContext() == null){
  		UKDataContext.setApplicationContext(event.getApplicationContext());
  	}
  	sysDicRes = event.getApplicationContext().getBean(SysDicRepository.class) ;
  	blackListRes = event.getApplicationContext().getBean(BlackListRepository.class) ;
  	List<SysDic> sysDicList = sysDicRes.findAll() ;
  	
  	for(SysDic dic : sysDicList){
  		CacheHelper.getSystemCacheBean().put(dic.getId(), dic, dic.getOrgi());
	if(dic.getParentid().equals("0")){
		List<SysDic> sysDicItemList = new ArrayList<SysDic>();
		for(SysDic item : sysDicList){
			if(item.getDicid()!=null && item.getDicid().equals(dic.getId())){
				sysDicItemList.add(item) ;
			}
		}
		CacheHelper.getSystemCacheBean().put(dic.getCode(), sysDicItemList, dic.getOrgi());
	}
}
  	List<BlackEntity> blackList = blackListRes.findByOrgi(UKDataContext.SYSTEM_ORGI) ;
  	for(BlackEntity black : blackList){
  		if(!StringUtils.isBlank(black.getUserid())) {
   		if(black.getEndtime()==null || black.getEndtime().after(new Date())){
   			CacheHelper.getSystemCacheBean().put(black.getUserid(), black, black.getOrgi());
   		}
  		}
  	}
  	/**
  	 * 加载系统全局配置
  	 */
  	SystemConfigRepository systemConfigRes = event.getApplicationContext().getBean(SystemConfigRepository.class) ;
  	SystemConfig config = systemConfigRes.findByOrgi(UKDataContext.SYSTEM_ORGI) ;
  	if(config != null){
  		CacheHelper.getSystemCacheBean().put("systemConfig", config, UKDataContext.SYSTEM_ORGI);
  	}
  	GenerationRepository generationRes = event.getApplicationContext().getBean(GenerationRepository.class) ;
  	List<Generation> generationList = generationRes.findAll() ;
  	for(Generation generation : generationList){
  		CacheHelper.getSystemCacheBean().setAtomicLong(UKDataContext.ModelType.WORKORDERS.toString(), generation.getStartinx());
  	}
  	
  	UKTools.initSystemArea();
  	
  	UKTools.initSystemSecField(event.getApplicationContext().getBean(TablePropertiesRepository.class));
  	//UKTools.initAdv();//初始化广告位
  }
 
Example 18
Source File: OrderApplication.java    From minnal with Apache License 2.0 4 votes vote down vote up
public OrderApplication() {
	ConvertUtils.register(EnumConverter.instance, Order.Status.class);
	ConvertUtils.register(EnumConverter.instance, OrderItem.Status.class);
}
 
Example 19
Source File: ConvertUtil.java    From feilong-core with Apache License 2.0 2 votes vote down vote up
/**
 * Register simple date locale converter.
 *
 * @param pattern
 *            the pattern
 * @since 1.11.2
 */
public static void registerSimpleDateLocaleConverter(String pattern){
    DateLocaleConverter dateLocaleConverter = new DateLocaleConverter(null, Locale.getDefault(), pattern);
    ConvertUtils.register(dateLocaleConverter, Date.class);
}