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++) { if ("".equals(arrayKey[i]) || "".equals(arrayValue[i]) || "".equals(arrayType[i])) { continue; } 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; }
protected void setUp() { field = new Field(); field.setProperty(BIG_DECIMAL_PROPERTY); oldConverter = ConvertUtils.lookup(BigDecimal.class); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); }
static { DateConverter converter = new DateConverter(); String[] patterns = {"yyyy-MM-dd HH:mm:ss"}; converter.setPatterns(patterns); ConvertUtils.register(converter, Date.class); ConvertUtils.register(converter, String.class); }
public void init(ActionServlet servlet, ModuleConfig config) { DateConverter converterDate = new DateConverter(); converterDate.setPattern("E MMM dd HH:mm:ss z yyyy"); ConvertUtils.register(converterDate, Date.class); ConvertUtils.register(new NestedWidgetsConverter(), NestedWidgets.class); }
public static Object convertStringToObject(String 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 convertReflectionExceptionToUnchecked(e); } }
/** * 转换字符串类型到 toType 类型, 或 toType 转为字符串 * * @param value: 待转换的字符串 * @param toType: 提供类型信息的 Class, 可以是基本数据类型的包装类或指定格式日期型 * @return */ public static <T> T convertValue(Object value, Class<T> 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 (T) ConvertUtils.convert(value, toType); } catch (Exception e) { e.printStackTrace(); throw convertToUncheckedException(e); } }
/** * Adds the type and value of a method parameter to the internal lists. * * @param param The parameter object that holds the type and value information in a string manner. * @throws MethodParamException If the parameter type cannot be found or If the parameter string * value cannot be converted into an object defined by the parameter type. */ public void add(MessageParam param) throws MethodParamException { try { Class type = null; try { type = Class.forName(param.getType(), true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { // this happens if guidancer.datatype.Variable is used! type = Class.forName( String.class.getName(), true, Thread.currentThread().getContextClassLoader()); } String stringValue = param.getValue() == null ? StringConstants.EMPTY : param.getValue(); Object objectValue = ConvertUtils.convert(stringValue, type); if (objectValue == null || !type.isAssignableFrom(objectValue.getClass())) { throw new MethodParamException( "Failed converting " //$NON-NLS-1$ + stringValue + " into an instance of " + type, param); //$NON-NLS-1$ } m_types.add(type); m_objectValues.add(objectValue); } catch (ClassNotFoundException e) { throw new MethodParamException("Action parameter type not found: " + e, param); // $NON-NLS-1$ } }
/** * @param filterName 比较属性字符串,含待比较的比较类型、属性值类型及属性列表. eg. LIKES_NAME_OR_LOGIN_NAME * @param value 待比较的值. */ public PropertyFilter(final String filterName, final Object value) { String firstPart = StringUtils.upperCase(StringUtils.substringBefore(filterName, "_")); String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1); String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length()); try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); } catch (RuntimeException e) { throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性比较类型.", e); } try { propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性值类型.", e); } String propertyNameStr = StringUtils.substringAfter(filterName, "_"); // AssertUtils.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter名称" + filterName + // "没有按规则编写,无法得到属性名称."); propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR); this.matchValue = value; if (null == value || !String.class.equals(value.getClass())) { return; } if (!String.class.equals(propertyClass)) { this.matchValue = ConvertUtils.convert((String) value, propertyClass); } }
/** * String->Object. * * @param value 待转换的字符串. * @param toType 转换目标类型. * @return the object */ public static Object fromString(String value, Class<?> toType) { try { return ConvertUtils.convert(value, toType); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } }
/** * 商品在庫表リスト取得処理 * * @param form * @return * @throws IOException * @throws SQLException * @throws IllegalAccessException * @throws InvocationTargetException */ public static List<BookItemStock> getBookItemStockList(BookItemForm form) throws IOException, SQLException, IllegalAccessException, InvocationTargetException { BookItemStockDAO dao = new BookItemStockDAO(TransactionInfo.getConnection()); List<BookItemStock> bookItemStockList = new ArrayList<BookItemStock>(); List<Object> params = new ArrayList<Object>(); StringBuilder sql = new StringBuilder(); sql.append(choiceSQLSelect(form, params)); sql.append(CommonConstants.HALF_SPACE); sql.append(choiceSQLSort(form)); List<CommonDTO> retList = dao.select(sql.toString(), params); for (CommonDTO dto : retList) { BookItemStock bookItemStock = new BookItemStock(); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); BeanUtils.copyProperties(bookItemStock, SerializationUtils.clone((BookItemStockDTO) dto)); bookItemStock.setKabusoku( BookItemCommonBL.calcKabusoku(bookItemStock.getProperStock(), bookItemStock.getStock())); bookItemStockList.add(bookItemStock); } return bookItemStockList; }
/** * Object -> String. * * @param object the object * @return the string */ public static String toString(Object object) { try { return ConvertUtils.convert(object); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } }
public static Object convertStringToObject(String value, Class<?> toType) { try { return org.apache.commons.beanutils.ConvertUtils.convert(value, toType); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } }
protected Digester getDigester() { Digester digester = new Digester(); ConvertUtils.register(DateUtils.getGMTConverter(), Date.class); ConvertUtils.register(new EveRaceConverter(), EveRace.class); ConvertUtils.register(new EveBloodlineConverter(), EveBloodline.class); ConvertUtils.register(new EveAncestryConverter(), EveAncestry.class); digester.setValidating(false); digester.addObjectCreate("eveapi", clazz); digester.addSetProperties("eveapi"); digester.addObjectCreate("eveapi/error", ApiError.class); digester.addSetProperties("eveapi/error"); digester.addBeanPropertySetter("eveapi/error"); digester.addSetNext("eveapi/error", "setError"); digester.addBeanPropertySetter("eveapi/currentTime"); digester.addBeanPropertySetter("eveapi/cachedUntil"); return digester; }
/** 从request中获得Entity的id,并判断其有效性. */ protected Serializable getEntityId(HttpServletRequest request) { String idString = request.getParameter(idName); try { return (Serializable) ConvertUtils.convert(idString, idClass); } catch (NumberFormatException e) { throw new IllegalArgumentException("Wrong when get id from request"); } }
/** * 基于Apache BeanUtils转换对象到相应类型. * * @param value 待转换的对象. * @param toType 转换目标类型. */ public static Object convert(Object value, Class<?> toType) { if (value == null || value.getClass().equals(toType)) return value; try { return org.apache.commons.beanutils.ConvertUtils.convert(value, toType); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } }
/** * Realiza a cópia dos atributos em comum dos objetos. * * @param origem a instância que contém os dados a serem copiados. * @param destino a instância que irá receber a cópia dos dados. */ public static void copiarAtributos(Object origem, Object destino) { try { java.util.Date defaultValue = null; DateConverter converter = new DateConverter(defaultValue); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(converter, java.util.Date.class); ConvertUtils.register(new BigDecimalConverter(null), java.math.BigDecimal.class); BeanUtils.copyProperties(destino, origem); } catch (IllegalAccessException e) { LOG.trace( "Ocorreu um IllegalAccessException ao realizar a copia dos dados em copiarAtributos.", e); } catch (InvocationTargetException e) { LOG.trace( "Ocorreu um InvocationTargetException ao realizar a copia dos dados em copiarAtributos.", e); } }
public static <T> T convert2(String value, Class<T> toType) { if (toType == String.class) return (T) value; try { return (T) org.apache.commons.beanutils.ConvertUtils.convert(value.trim(), toType); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } }
/** Creates a new instance of {@link CoberturaPublisher} from a submitted form. */ @Override public CoberturaPublisher newInstance(StaplerRequest req, JSONObject formData) throws FormException { CoberturaPublisher instance = req.bindJSON(CoberturaPublisher.class, formData); ConvertUtils.register(CoberturaPublisherTarget.CONVERTER, CoverageMetric.class); List<CoberturaPublisherTarget> targets = req.bindParametersToList(CoberturaPublisherTarget.class, "cobertura.target."); instance.setTargets(targets); return instance; }
/** 通过编号获取内容标题 */ public List<Object[]> findByIds(String ids) { List<Object[]> list = Lists.newArrayList(); Long[] idss = (Long[]) ConvertUtils.convert(StringUtils.split(ids, ","), Long.class); if (idss.length > 0) { List<Link> l = linkDao.findByIdIn(idss); for (Link e : l) { list.add(new Object[] {e.getId(), StringUtils.abbr(e.getTitle(), 50)}); } } return list; }
/** * 基于Apache BeanUtils转换字符串到相应类型. * * @param value 待转换的字符串. * @param toType 转换目标类型. */ public static Object convert(String value, Class<?> toType) { if (toType == String.class) return value; try { return org.apache.commons.beanutils.ConvertUtils.convert(value.trim(), toType); } catch (Exception e) { if (Date.class.equals(toType)) { // 如果转换对象为Date,则试着把字符串转换为long,再把long转换为Date try { Long v = (Long) org.apache.commons.beanutils.ConvertUtils.convert(value.trim(), Long.class); return org.apache.commons.beanutils.ConvertUtils.convert(v, toType); } catch (Exception e1) { throw convertReflectionExceptionToUnchecked(e); } } throw convertReflectionExceptionToUnchecked(e); } }
/** * @param filterName * @param value */ public PropertyFilter(final String filterName, final String value) { String matchTypeStr; String matchPattenCode = LikeMatchPatten.ALL.toString(); String matchTypeCode; String propertyTypeCode; if (filterName.contains("LIKE") && filterName.charAt(0) != 'L') { matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX); matchPattenCode = StringUtils.substring(matchTypeStr, 0, 1); matchTypeCode = StringUtils.substring(matchTypeStr, 1, matchTypeStr.length() - 1); propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length()); } else { matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX); matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1); propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length()); } try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); likeMatchPatten = Enum.valueOf(LikeMatchPatten.class, matchPattenCode); } catch (RuntimeException e) { throw new IllegalArgumentException( "filter name: " + filterName + "Not prepared in accordance with rules, not get more types of property.", e); } try { propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException( "filter name: " + filterName + "Not prepared in accordance with the rules, attribute value types can not be.", e); } String propertyNameStr = StringUtils.substringAfter(filterName, PARAM_PREFIX); propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR); Validate.isTrue( propertyNames.length > 0, "filter name: " + filterName + "Not prepared in accordance with the rules, property names can not be."); this.propertyValue = ConvertUtils.convert(value, propertyType); }
public static void setPropertyValue( final Object bean, final PropertyDescriptor descriptor, Object value) { notNull(bean); notNull(descriptor); final String name = descriptor.getName(); final Class<?> type = descriptor.getPropertyType(); if (value != null && !type.isAssignableFrom(value.getClass())) { try { value = ConvertUtils.convert(value, type); LOGGER.debug( "Successfully converted value of type {} to type {}.", value.getClass().getName(), type); } catch (ConversionException x) { throw new IllegalArgumentException( format( "Cannot convert value %s (instance of %s) to type %s.", value, value.getClass(), type), x); } } LOGGER.debug("{}.setPropertyValue({}, {}, {})", bean.getClass().getName(), name, value); final Method method = descriptor.getWriteMethod(); if (method == null) { throw new RuntimeException(format("No write method for property \"%s\"?", name)); } try { method.invoke(bean, value); } catch (IllegalAccessException x) { LOGGER.error( String.format( "An exception was thrown while attempting to set property %s to value %s of an instance of %s.", name, value, bean.getClass()), x); throw new RuntimeException(x); } catch (IllegalArgumentException x) { LOGGER.error( String.format( "An exception was thrown while attempting to set property %s to value %s of an instance of %s.", name, value, bean.getClass()), x); throw new RuntimeException(x); } catch (InvocationTargetException x) { LOGGER.error( String.format( "An exception was thrown while attempting to set property %s to value %s of an instance of %s.", name, value, bean.getClass()), x); throw new RuntimeException(x); } }
@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; }
static { ConvertUtils.register( new Converter() { public Object convert(final Class cls, final Object o) { if (o == null) { throw new IllegalArgumentException("Object to convert is null"); } return new Integer(o.toString()); } }, Number.class); ConvertUtils.register( new Converter() { public Object convert(final Class cls, final Object o) { if (o == null) { throw new IllegalArgumentException("Object to convert is null"); } try { return DateUtils.parseDate( o.toString(), new String[] { "yyyy-MM-dd", "HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss", "yyMMddHHmmssZ", "yyyy-MM-dd'T'HH:mm:ssZ", "yyMMddHHmmss", "yyyy-MM-dd HH:mm:ss" }); } catch (java.text.ParseException pe) { throw new RuntimeException("Do not know how to convert " + o.toString(), pe); } } }, Date.class); }
public List<Qtree> listQtree(String volume) { NaElement elem = new NaElement("qtree-list-iter"); if (volume != null && !volume.isEmpty()) { NaElement qtreeAttrs = new NaElement("qtree-info"); qtreeAttrs.addNewChild("volume", volume); NaElement query = new NaElement("query"); query.addChildElem(qtreeAttrs); elem.addChildElem(query); } NaElement resultElem = null; String tag = null; List<Qtree> qtrees = Lists.newArrayList(); try { do { NaElement results = server.invokeElem(elem); tag = results.getChildContent("next-tag"); resultElem = results.getChildByName("attributes-list"); if (resultElem != null) { // Get the number of records returned by API. for (NaElement qtreeElem : (List<NaElement>) resultElem.getChildren()) { if (qtreeElem != null) { Qtree qtree = new Qtree(); qtree.setId( (Integer) ConvertUtils.convert(qtreeElem.getChildContent("id"), Integer.class)); qtree.setOplocks(qtreeElem.getChildContent("oplocks")); qtree.setOwningVfiler(qtreeElem.getChildContent("vserver")); qtree.setQtree(qtreeElem.getChildContent("qtree")); qtree.setSecurityStyle(qtreeElem.getChildContent("security-style")); qtree.setStatus(qtreeElem.getChildContent("status")); qtree.setVolume(qtreeElem.getChildContent("volume")); qtrees.add(qtree); } } } if (tag != null && !tag.isEmpty()) { elem = new NaElement("qtree-list-iter"); elem.addNewChild("tag", tag); } } while (tag != null && !tag.isEmpty()); } catch (Exception e) { throw createError(elem, e); } return qtrees; }
public static <T> T request2Bean(HttpServletRequest request, Class<T> clazz) { T t = null; try { t = clazz.newInstance(); ConvertUtils.register(new DateLocaleConverter(), Date.class); @SuppressWarnings("rawtypes") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getParameter(name); BeanUtils.setProperty(t, name, value); } } catch (Exception e) { throw new RuntimeException(e); } return t; }
@SuppressWarnings("rawtypes") public Object convertValue( Map context, Object target, Member member, String propertyName, Object value, Class toType) { if (value == null) { return super.convertValue(context, target, member, propertyName, value, toType); } if (Date.class.isAssignableFrom(value.getClass()) && toType == String.class) { return DateUtil.format((Date) value, "yyyy-MM-dd HH:mm:ss"); } else if (Date.class.isAssignableFrom(toType)) { try { DateFormat dateFormat = (DateFormat) ClassUtil.getParamAnno((Method) member); return DateUtil.parse( StringUtil.nullValue(ClassUtil.isArray(value) ? Array.get(value, 0) : value), dateFormat.pattern()); } catch (RuntimeException e) { LOG.error(e.getMessage(), e); return ConvertUtils.convert(value, Date.class); } } else if (ClassUtil.isArray(value)) { StringBuilder buffer = new StringBuilder(); for (int i = 0, len = Array.getLength(value); i < len; i++) { buffer.append( this.convertValue(context, target, member, propertyName, Array.get(value, i), toType)); if (i != len - 1) { buffer.append(";"); } } return buffer.toString(); } else if (ClassUtil.isArray(toType)) { String[] array = StringUtil.tokenizeToStringArray(value.toString(), ";"); Object ret = Array.newInstance(toType.getComponentType(), array.length); for (int i = 0; i < array.length; i++) { Array.set( ret, i, this.convertValue( context, target, member, propertyName, array[i], toType.getComponentType())); } return ret; } else { return super.convertValue(context, target, member, propertyName, value, toType); } }
/** configure. */ static void configureBeanUtils() { BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance(); if (beanUtilsBean.getClass() != BeanUtilsBean.class) { throw new IllegalStateException( "Someone has already switched the default org.apache.commons.beanutils.BeanUtilsBean instance"); //$NON-NLS-1$ } if (beanUtilsBean.getConvertUtils().getClass() != ConvertUtilsBean.class) { throw new IllegalStateException( "Someone has already switched the default org.apache.commons.beanutils.ConvertUtilsBean instance"); //$NON-NLS-1$ } BeanUtilsBean.setInstance(new BeanUtilsBean(new EnumAwareConvertUtilsBean())); DateTimeConverter dtConverter = new DateConverter(); dtConverter.setPattern(Bo2UtilsEnvironment.getIsoDateFormatPattern()); ConvertUtils.register(dtConverter, java.util.Date.class); }
/** * Returns a {@link Converter} that can convert values to the target value type. If the target * entity type + property has a custom converter defined in the GTFS entity schema, we will use * that as instead. * * @param targetEntityType the target entity type whose property will be updated. * @param targetPropertyName the target property name for the property that will be updated on the * target entity. * @param targetValueType the target value type we wish to convert to */ public Converter resolveConverter( Class<?> targetEntityType, String targetPropertyName, Class<?> targetValueType) { SingleFieldMapping mapping = _schemaCache.getFieldMappingForCsvFieldName(targetEntityType, targetPropertyName); if (mapping == null) { mapping = _schemaCache.getFieldMappingForObjectFieldName(targetEntityType, targetPropertyName); } if (mapping != null) { if (mapping instanceof ConverterFactory) { ConverterFactory factory = (ConverterFactory) mapping; return factory.create(_reader.getContext()); } if (mapping instanceof Converter) { return (Converter) mapping; } } return ConvertUtils.lookup(targetValueType); }
public TVShow getShowInfo(String name) { log.info("getting show info for {}", name); ConvertUtils.register(getDateConverter(), Date.class); try { int showid = getShowId(name); if (showid == -1) { return null; } // no show by that name Response response = client.get("http://www.tvrage.com/feeds/full_show_info.php?sid=" + showid); log.debug("Found TV Show named {} at http://www.tvrage.com/feeds/full_show_info.php", name); Digester digest = new Digester(); digest.addObjectCreate("Show", TVShow.class); digest.addBeanPropertySetter("Show/name"); digest.addBeanPropertySetter("Show/showid", "id"); digest.addBeanPropertySetter("Show/started", "startedDate"); digest.addBeanPropertySetter("Show/origin_country", "country"); digest.addBeanPropertySetter("Show/status"); digest.addBeanPropertySetter("Show/runtime"); digest.addObjectCreate("Show/Episodelist/Season", Season.class); digest.addSetProperties("Show/Episodelist/Season", "no", "number"); digest.addSetNext("Show/Episodelist/Season", "addSeason"); digest.addObjectCreate("Show/Episodelist/Season/episode", Episode.class); digest.addSetNext("Show/Episodelist/Season/episode", "addEpisode"); digest.addBeanPropertySetter("Show/Episodelist/Season/episode/seasonnum", "episodeNum"); digest.addBeanPropertySetter("Show/Episodelist/Season/episode/epnum", "absoluteEpisodeNum"); digest.addBeanPropertySetter("Show/Episodelist/Season/episode/prodnum", "productionNum"); digest.addBeanPropertySetter("Show/Episodelist/Season/episode/airdate", "airDate"); digest.addBeanPropertySetter("Show/Episodelist/Season/episode/link", "detailsLink"); digest.addBeanPropertySetter("Show/Episodelist/Season/episode/title"); return (TVShow) digest.parse(response.getBody()); } catch (Exception e) { log.error("error fetching TV show data for show " + name, e); return null; } }