Example #1
0
  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);
  }
Example #2
0
  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);
  }
Example #3
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;
  }
  /**
   * 商品在庫表リスト取得処理
   *
   * @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;
  }
Example #5
0
  protected void setUp() {
    field = new Field();
    field.setProperty(BIG_DECIMAL_PROPERTY);

    oldConverter = ConvertUtils.lookup(BigDecimal.class);
    ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
  }
Example #6
0
 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;
 }
 /**
  * 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);
   }
 }
 /** 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;
 }
Example #9
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);
   }
 }
Example #10
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);
    }
  }
Example #11
0
 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);
 }
Example #12
0
 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;
 }
Example #13
0
  /** 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);
  }
  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);
  }
  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;
    }
  }
Example #16
0
  /**
   * 将map转化为bean
   *
   * @param map
   * @param beanClass
   * @return
   * @throws Exception
   */
  public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
    if (map == null) return null;

    Object obj = beanClass.newInstance();
    ConvertUtils.register(
        new Converter() {
          @SuppressWarnings("rawtypes")
          @Override
          public Object convert(Class arg0, Object arg1) {
            if (arg1 == null) {
              return null;
            }
            if (!(arg1 instanceof String)) {
              throw new ConversionException("只支持字符串转换 !");
            }
            String str = (String) arg1;
            if (str.trim().equals("")) {
              return null;
            }

            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            try {
              return sd.parse(str);
            } catch (ParseException e) {
              throw new RuntimeException(e);
            }
          }
        },
        java.util.Date.class);

    try {
      BeanUtils.populate(obj, map);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return obj;
  }
Example #17
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;
  }
Example #18
0
 static {
   DateConverter dateConverter = new DateConverter();
   dateConverter.setPattern(Application.DATE_FORMAT);
   ConvertUtils.register(dateConverter, Date.class);
 }
 // 注册自定义的转换类,解决提交form时日期、时间不能为空的问题
 static {
   ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
   ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
 }
Example #20
0
 /**
  * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔.
  *
  * @param patterns the patterns
  */
 public static void registerDateConverter(String... patterns) {
   DateConverter dc = new DateConverter();
   dc.setUseLocaleFormat(true);
   dc.setPatterns(patterns);
   ConvertUtils.register(dc, Date.class);
 }
Example #21
0
 // 注册转换器
 static {
   ConvertUtils.register(new DateConverter(null), Date.class);
 }
 public void init(ActionServlet arg0, ModuleConfig arg1) throws ServletException {
   ConvertUtils.register(new DateConvert(), Date.class);
 }
Example #23
0
 static {
   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);
 }
Example #24
0
  private void updateCover(
      HttpServletRequest request, HttpServletResponse response, final String method)
      throws FileUploadException, ServletException, IOException, IllegalAccessException,
          InvocationTargetException {
    List<String> types = Arrays.asList(".jpg", ".gif", ".png", ".jpeg"); // supported
    // type

    DiskFileItemFactory dfi = new DiskFileItemFactory(); // apache's
    // component

    dfi.setSizeThreshold(1024 * 1024); // 1M, and default is 10k, and
    // excessed will be saved in the
    // cache file
    String path = getServletContext().getRealPath("/WEB-INF/temp");
    dfi.setRepository(new File(path)); // temporary cached file

    ServletFileUpload sf = new ServletFileUpload(dfi);
    sf.setHeaderEncoding("utf-8");
    // sf.setFileSizeMax(1024*1024*5); //set single file's max size

    List<FileItem> lf = sf.parseRequest(new ServletRequestContext(request));
    Map<String, String> map = new HashMap<String, String>();
    List<String> idf = new LinkedList<String>();
    FileItem fi = null; // for stream file
    String ids[];

    for (FileItem item : lf) {
      if (item.isFormField()) { // ordinary input
        String name = item.getFieldName();
        String value = item.getString("utf-8");
        map.put(name, value);
        if ("category".equals(name)) {
          idf.add(value);
        }
        System.out.println(name + " " + value);
      } else { // stream
        String name = item.getName();
        if (name == null || "".equals(name)) {
          continue;
        }
        String ext = name.substring(name.lastIndexOf("."));
        System.out.println(ext);
        if (!types.contains(ext.toLowerCase())) {
          request.setAttribute("message", "sorryia..  i don't support type " + ext);
          return;
        }

        fi = item;
      }
    }

    Book book = new Book();
    ConvertUtils.register(new DateLocaleConverter(), Date.class);
    BeanUtils.populate(book, map);
    BookDaoImpl bdi = new BookDaoImpl();
    ids = new String[idf.size()];
    idf.toArray(ids);
    int id;

    if (method.equals(BOOK_ADD)) {
      id = bdi.add(book, ids);
      request.setAttribute("message", "add book successfully...");
    } else {
      id = Integer.parseInt(map.get("id"));
      book.setId(id);
      bdi.update(book);
      bdi.updateCategory(id, ids);
      request.setAttribute("message", "update book successfully...");
    }

    if (fi != null) { // upload file
      InputStream is = fi.getInputStream();
      String Spath = getServletContext().getRealPath("/img/bookcover/");
      System.out.println(Spath);
      FileOutputStream fos = new FileOutputStream(new File(Spath + id + ".jpg"));
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = is.read(b)) > 0) {
        fos.write(b, 0, len);
      }
      fos.close();
      is.close();
      fi.delete(); // the temporary file would be deleted.
    }
  }
Example #25
0
 static {
   ConvertUtils.register(new SearchFilterConverter(), SearchFilter.class);
 }
Example #26
0
 public static void registerConverters() {
   ConvertUtils.register(new StringConverter(), String.class);
   // date
   ConvertUtils.register(new DateConverter(null), java.util.Date.class);
   ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
   ConvertUtils.register(new SqlTimeConverter(null), Time.class);
   ConvertUtils.register(new SqlTimestampConverter(null), Timestamp.class);
   // number
   ConvertUtils.register(new BooleanConverter(null), Boolean.class);
   ConvertUtils.register(new ShortConverter(null), Short.class);
   ConvertUtils.register(new IntegerConverter(null), Integer.class);
   ConvertUtils.register(new LongConverter(null), Long.class);
   ConvertUtils.register(new FloatConverter(null), Float.class);
   ConvertUtils.register(new DoubleConverter(null), Double.class);
   ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
   ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);
 }
Example #27
0
 protected void tearDown() {
   field = null;
   ConvertUtils.register(oldConverter, BigDecimal.class);
 }
Example #28
0
 private static void registerDateConverter() {
   DateConverter dc = new DateConverter();
   dc.setUseLocaleFormat(true);
   dc.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"});
   org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class);
 }
 /** 定义Apache BeanUtils日期Converter的格式: yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss */
 private static void registerDateConverter() {
   DapDateConvert dc = new DapDateConvert();
   org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class);
   org.apache.commons.beanutils.ConvertUtils.register(dc, String.class);
 }