Пример #1
0
 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);
   }
 }
Пример #2
0
  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;
  }
Пример #3
0
 /**
  * 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);
   }
 }
Пример #4
0
 /**
  * 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);
   }
 }
Пример #5
0
 /**
  * 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$
   }
 }
Пример #6
0
  /**
   * @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);
    }
  }
Пример #7
0
 /** 从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");
   }
 }
  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);
    }
  }
  /**
   * 基于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);
    }
  }
Пример #10
0
 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);
   }
 }
Пример #11
0
 /** 通过编号获取内容标题 */
 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);
    }
  }
Пример #13
0
  public static void main(String[] args) {
    String convert = ConvertUtils.convert(LocalDateTime.now());
    System.out.println(convert);
    Integer convert2 = (Integer) ConvertUtils.convert("12", Integer.class);
    System.out.println(convert2);

    try {
      Object convert3 = ConvertUtils.convert(LocalDateTime.now().toString(), LocalDateTime.class);
      System.out.println(convert3);
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }

    ConvertUtils.register(new ApidocsPractice.LocalDateTimeConverter(), LocalDateTime.class);
    LocalDateTime convert3 =
        (LocalDateTime) ConvertUtils.convert(LocalDateTime.now().toString(), LocalDateTime.class);
    System.out.println(convert3);

    Long convert4 = (Long) ConvertUtils.convert(12L, Long.class);
    Preconditions.checkArgument(convert4.compareTo(12L) == 0);
  }
Пример #14
0
 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);
   }
 }
Пример #15
0
  /**
   * @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);
  }
Пример #16
0
  /**
   * 转换字符串类型到 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);
    }
  }
  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;
  }
Пример #18
0
 @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);
   }
 }
Пример #19
0
  @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;
  }
 public static String convert(Object value) {
   return org.apache.commons.beanutils.ConvertUtils.convert(value);
 }