Beispiel #1
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");
    do {
      Connection connection = null;
      is_importing = true;
      try {
        connection =
            PoolHelper.getInstance().getConnection(com.wofu.ecommerce.taobao.Params.dbname);
        lasttime =
            PublicUtils.getConfig(
                connection,
                lasttimeconfvalue,
                Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));

        getRefundBillList(connection);
      } catch (Exception e) {
        try {
          if (connection != null && !connection.getAutoCommit()) connection.rollback();
        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        is_importing = false;
        try {
          if (connection != null) connection.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime
          < (long) (com.wofu.ecommerce.taobao.Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Beispiel #2
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");
    do {
      Connection connection = null;
      is_exporting = true;
      try {
        connection = PoolHelper.getInstance().getConnection(Params.dbname);

        delivery(connection);

        // modifiRemark(connection);

      } catch (Exception e) {
        try {
          if (connection != null && !connection.getAutoCommit()) connection.rollback();
        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        is_exporting = false;
        try {
          if (connection != null) connection.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime < (long) (Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Beispiel #3
0
  public void run() {

    Log.info(jobName, "启动[" + jobName + "]模块");
    do {
      Connection connection = null;

      try {
        connection = PoolHelper.getInstance().getConnection(com.wofu.ecommerce.ylw.Params.dbname);
        getRefund(connection);

      } catch (Exception e) {
        try {
          e.printStackTrace();
          if (connection != null && !connection.getAutoCommit()) connection.rollback();
        } catch (Exception e1) {
          Log.error(jobName, "回滚事务失败");
        }
        Log.error("105", jobName, Log.getErrorMessage(e));
      } finally {

        try {
          if (connection != null) connection.close();
        } catch (Exception e) {
          Log.error(jobName, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime
          < (long) (Params.waittime * 1000 * Params.timeInterval))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobName, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Beispiel #4
0
  public void run() {

    Properties prop = StringUtil.getStringProperties(this.getExecuteobj().getParams());

    url = prop.getProperty("url");
    tradecontactid = prop.getProperty("tradecontactid");
    username = prop.getProperty("username");
    app_id = prop.getProperty("app_id");
    secret = prop.getProperty("secret");
    session = prop.getProperty("session");
    System.out.println(url);
    System.out.println(tradecontactid);
    System.out.println(username);
    System.out.println(app_id);
    System.out.println(secret);
    System.out.println(session);
    try {

      updateJobFlag(1);

      synStock();

      UpdateTimerJob();

      Log.info(
          jobName,
          "执行作业成功 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] 下次处理时间: "
              + this.datetimeformat.format(this.getExecuteobj().getNextactive()));

    } catch (Exception e) {
      try {
        if (this.getExecuteobj().getSkip() == 1) {
          UpdateTimerJob();
        } else UpdateTimerJob(Log.getErrorMessage(e));

        if (this.getConnection() != null && !this.getConnection().getAutoCommit())
          this.getConnection().rollback();

        if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
          this.getExtconnection().rollback();

      } catch (Exception e1) {
        Log.error(jobName, "回滚事务失败");
      }
      Log.error(jobName, "错误信息:" + Log.getErrorMessage(e));

      Log.error(
          jobName,
          "执行作业失败 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] \r\n  "
              + Log.getErrorMessage(e));

    } finally {
      try {
        updateJobFlag(0);
      } catch (Exception e) {
        Log.error(jobName, "更新处理标志失败");
      }

      try {
        if (this.getConnection() != null) this.getConnection().close();
        if (this.getExtconnection() != null) this.getExtconnection().close();

      } catch (Exception e) {
        Log.error(jobName, "关闭数据库连接失败");
      }
    }
  }
Beispiel #5
0
  private void synStock() throws Exception {
    // 店铺同步比例
    double synrate = 1;
    Log.info(username, "开始同步商品库存");

    StringBuffer updateItemsXML = new StringBuffer();

    String sql =
        "select orgid from ecs_tradecontactorgcontrast with(nolock) where tradecontactid="
            + tradecontactid;
    int orgid = this.getDao().intSelect(sql);

    sql = "update ecs_stockconfig set errflag=0,errmsg='' where orgid=" + orgid;
    this.getDao().execute(sql);

    sql = "update ecs_stockconfigsku set errflag=0,errmsg='' where orgid=" + orgid;
    this.getDao().execute(sql);
    // 店铺同步比例表
    sql = "select synrate from ecs_shopglobalconfig where shopOrgId=" + orgid;
    String temp = this.getDao().strSelect(sql);
    if (!"".equals(temp)) synrate = Float.parseFloat(temp);
    int n = 0;

    for (int k = 0; k < 10; ) {
      try {
        sql = "select * from ecs_stockconfig with(nolock) where orgid=" + orgid;
        Vector vtstockconfig = this.getDao().multiRowSelect(sql);
        for (int i = 0; i < vtstockconfig.size(); i++) {
          try {
            Hashtable htstockconfig = (Hashtable) vtstockconfig.get(i);

            ECS_StockConfig stockconfig = new ECS_StockConfig();
            stockconfig.getMapData(htstockconfig);

            String itemid = stockconfig.getItemid();
            Log.info("商品ID:" + stockconfig.getItemid() + " 货号:" + stockconfig.getItemcode());

            if (stockconfig.getIsneedsyn() == 0) {
              Log.info(username, "配置不需要同步库存,货号:" + stockconfig.getItemcode());
              continue; // 不需要同步
            }

            sql =
                "select * from ecs_stockconfigsku with(nolock) where orgid="
                    + orgid
                    + " and itemid='"
                    + stockconfig.getItemid()
                    + "'";

            Vector vtstockconfigsku = this.getDao().multiRowSelect(sql);

            for (int j = 0; j < vtstockconfigsku.size(); j++) {
              try {
                Hashtable htstockconfigsku = (Hashtable) vtstockconfigsku.get(j);

                ECS_StockConfigSku stockconfigsku = new ECS_StockConfigSku();
                stockconfigsku.getMapData(htstockconfigsku);

                Log.info(
                    username,
                    "SKU:" + stockconfigsku.getSku() + " 原库存:" + stockconfigsku.getStockcount());

                boolean ismulti = false;
                boolean isfind = true;

                sql =
                    "select count(*) from barcode with(nolock) where custombc='"
                        + stockconfigsku.getSku()
                        + "'";
                if (this.getDao().intSelect(sql) == 0) {
                  sql =
                      "select count(*) from MultiSKURef where refcustomercode='"
                          + stockconfigsku.getSku()
                          + "'";
                  if (this.getDao().intSelect(sql) == 0) {
                    Log.warn(
                        username,
                        "找不到SKU【"
                            + stockconfigsku.getSku()
                            + "】对应的条码,商品标题:"
                            + stockconfig.getTitle());

                    stockconfigsku.setErrflag(1);
                    stockconfigsku.setErrmsg("找不到SKU【" + stockconfigsku.getSku() + "】对应的条码");
                    this.getDao().updateByKeys(stockconfigsku, "orgid,itemid,skuid");

                    stockconfig.setErrflag(1);
                    stockconfig.setErrmsg("找不到SKU【" + stockconfigsku.getSku() + "】对应的条码");
                    this.getDao().updateByKeys(stockconfig, "orgid,itemid");

                    isfind = false;
                    continue;
                  } else ismulti = true;
                }

                int qty = 0;

                if (isfind) {
                  if (ismulti) {
                    int minqty = 1000000;
                    sql =
                        "select customercode,qty from MultiSKURef where refcustomercode='"
                            + stockconfigsku.getSku()
                            + "'";
                    Vector multiskulist = this.getDao().multiRowSelect(sql);
                    for (Iterator itmulti = multiskulist.iterator(); itmulti.hasNext(); ) {
                      Hashtable skuref = (Hashtable) itmulti.next();
                      String customercode = skuref.get("customercode").toString();
                      double skurefqty = Double.valueOf(skuref.get("qty").toString()).doubleValue();
                      qty =
                          StockManager.getTradeContactUseableStock(
                              this.getDao().getConnection(),
                              Integer.valueOf(tradecontactid).intValue(),
                              customercode);

                      qty = (Double.valueOf(Math.ceil(qty / skurefqty))).intValue();

                      if (qty < minqty) {
                        minqty = qty;
                      }
                    }

                    qty = minqty;
                  } else {
                    qty =
                        StockManager.getTradeContactUseableStock(
                            this.getDao().getConnection(),
                            Integer.valueOf(tradecontactid).intValue(),
                            stockconfigsku.getSku());
                  }

                  if (qty < 0) qty = 0;
                }

                int addstockqty = 0;
                if (Math.abs(stockconfig.getAddstockqty()) < 1)
                  addstockqty =
                      Double.valueOf(Math.floor(qty * stockconfig.getAddstockqty())).intValue();
                else addstockqty = Double.valueOf(stockconfig.getAddstockqty()).intValue();
                // 如果可用库存加上需增加的库存小于等于警戒库存,则将库存同步为0
                if ((qty + addstockqty) <= stockconfig.getAlarmqty()) {
                  qty = 0;
                } else {
                  qty = qty + addstockqty;
                }

                Log.info("old qty: " + qty);
                qty = Double.valueOf(Math.floor(qty * synrate)).intValue();
                Log.info("new qty: " + qty);
                // 更新库存开始
                StockUtils.UpdateSkuStock(
                    this.getDao(),
                    orgid,
                    url,
                    app_id,
                    secret,
                    session,
                    stockconfigsku.getSku(),
                    qty,
                    stockconfig,
                    stockconfigsku);

              } catch (Exception ex) {
                if (this.getConnection() != null && !this.getConnection().getAutoCommit())
                  this.getConnection().rollback();

                if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
                  this.getExtconnection().rollback();
                Log.error(jobName, ex.getMessage());
              }
            }

            k = 0;
          } catch (Exception ex) {
            if (this.getConnection() != null && !this.getConnection().getAutoCommit())
              this.getConnection().rollback();

            if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
              this.getExtconnection().rollback();
            Log.error(jobName, ex.getMessage());
          }
        }
        break;

      } catch (Exception e) {
        if (++k >= 10) throw e;
        if (this.getConnection() != null && !this.getConnection().getAutoCommit())
          this.getConnection().rollback();

        if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
          this.getExtconnection().rollback();
        Log.warn(jobName + ", 远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));

        Thread.sleep(10000L);
      }
    }
  }
Beispiel #6
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");

    do {
      Connection conn = null;
      try {
        conn = PoolHelper.getInstance().getConnection(Params.dbname);
        Holder ask = new Holder();
        Holder message = new Holder();
        Holder error = new Holder();
        HeaderRequest request = new HeaderRequest();
        request.setAppKey(Params.Key);
        request.setAppToken(Params.Token);
        request.setCustomerCode(Params.customercode);
        ServiceForProduct_Service service = new ServiceForProduct_Service();
        ServiceForProduct info = service.getServiceForProductSOAP();
        // 取得要处理的数据的单号  这个单号对应barcodetranlist的sheetid
        Vector infsheetlist = FedexUtil.getInfDownNote(conn, "9901");
        // 每一个单号发送一次请求
        for (Iterator it = infsheetlist.iterator(); it.hasNext(); ) {
          Hashtable ht = (Hashtable) it.next();
          String sheetid = ht.get("OperData").toString();
          Integer serialid = (Integer) ht.get("SerialID");
          Log.info("sheetid: " + sheetid);
          // skuCategory 产品分类   这个还没有表数据关联的
          String sql =
              " select CustomBC skuNo,g.Name skuName, g.Name skuEnName,rtrim(d.skuCategory) as skuCategory,g.customno,g.deptid, isnull(g.postTaxNo,'"
                  + "GDO51311409230000003') applyEnterpriseCode,u.uom UOM ,0 barcodeType,substring(Spec,1,128) "
                  + "specificationsAndModels,hsCode,g.Price productDeclaredValue,g.Name hsGoodsName,b.applyEnterpriseCodeCIQ,"
                  + "cc.code originCountry,br.name brand,case when isnull(Weigh,1000)/1000<1 then 1 else isnull(Weigh,1000)"
                  + "/1000 end as weight ,case when isnull(NetWeigh,1000)/1000<1 then 1 else isnull(NetWeigh,1000)/1000 end as netWeight"
                  + " from BarcodeTranList a , Barcode b , Merchandise g , PostTariff p,unit u,"
                  + "countrycode cc ,dept d ,brand br where a.BarcodeID = b.BarcodeID and b.MID = g.MID and g.unitname="
                  + "u.unitname and cc.name=g.origin and g.PostTaxNo = p.Code and d.deptid=g.deptid and g.brandid=br.BrandID and SheetID = '"
                  + sheetid
                  + "'";
          boolean isSuccess = false;
          Vector vtsku = SQLHelper.multiRowSelect(conn, sql);
          for (int i = 0; i < vtsku.size(); i++) {
            Hashtable htsku = (Hashtable) vtsku.get(i);
            ProductInfo productInfo = new ProductInfo();
            productInfo.getMapData(htsku);
            info.createProduct(request, productInfo, ask, message, error);
            if ("1".equals(ask.value)) {
              isSuccess = true;
              /*
              conn.setAutoCommit(false);
              FedexUtil.bakcUpDownNote(conn,serialid);
              conn.commit();
              conn.setAutoCommit(true);
              **/
              Log.info("添加商品成功,sku: " + productInfo.getSkuNo());
            } else {
              isSuccess = false;
              Log.info("上传商品数据失败: " + message.value);
              List<ErrorType> type = (List<ErrorType>) error.value;
              for (Iterator t = type.iterator(); t.hasNext(); ) {
                ErrorType err = (ErrorType) t.next();
                Log.info("上传商品数据失败: " + err.getErrorMessage());
              }
            }
          }
          if (isSuccess) { // 处理成功备份接口数据
            conn.setAutoCommit(false);
            FedexUtil.bakcUpDownNote(conn, serialid);
            conn.commit();
            conn.setAutoCommit(true);
          }
        }

      } catch (Exception e) {
        try {
          if (conn != null && !conn.getAutoCommit()) {
            conn.rollback();
            conn.setAutoCommit(true);
          }

        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        e.printStackTrace();
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        try {
          if (conn != null) conn.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime < (long) (Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Beispiel #7
0
  public void getRefund(Connection conn) throws Exception {
    String resultText = "";
    for (int k = 0; k < 5; ) {
      try {
        // 获取到退货订单号
        String apiMethod = "suning.custom.batchrejectedOrd.query";
        HashMap<String, String> reqMap = new HashMap<String, String>();
        reqMap.put(
            "startTime",
            Formatter.format(
                new Date(System.currentTimeMillis() - daymillis), Formatter.DATE_TIME_FORMAT));
        reqMap.put("endTime", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("appSecret", Params.appsecret);
        map.put("appMethod", apiMethod);
        map.put("format", Params.format);
        map.put("versionNo", "v1.2");
        map.put("appKey", Params.appKey);
        // 发送请求
        String responseText = CommHelper.doRequest(map, Params.url);
        Log.info("退换货数据: " + responseText);
        // 把返回的数据转成json对象
        JSONObject responseObj = new JSONObject(responseText).getJSONObject("sn_responseContent");
        // 错误对象
        if (responseText.indexOf("sn_error") != -1) { // 发生错误
          String operCode = responseObj.getJSONObject("sn_error").getString("error_code");
          if (!"".equals(operCode)) {
            Log.error("苏宁获取退货订单", "获取退货订单失败,operCode:" + operCode);
          }
          return;
        }

        JSONArray ReturnCodeList =
            responseObj.getJSONObject("sn_body").getJSONArray("batchQueryRejectedOrd");
        for (int i = 0; i < ReturnCodeList.length(); i++) {
          try {
            String orderCode = ReturnCodeList.getJSONObject(i).getString("orderCode");
            Order o = new Order();
            OrderUtils.createRefundOrder(
                "生成苏宁退换货接口订单",
                conn,
                Params.tradecontactid,
                o,
                Params.url,
                Params.appKey,
                Params.appsecret,
                Params.format);
          } catch (Exception ex) {
            if (conn != null && !conn.getAutoCommit()) {
              conn.rollback();
            }
            Log.error(jobName, ex.getMessage());
            continue;
          }
        }

        break;

      } catch (Exception e) {
        if (++k >= 5) throw e;
        if (conn != null && !conn.getAutoCommit()) {
          conn.rollback();
        }
        Log.warn(jobName + " ,远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
  }
Beispiel #8
0
  private void getInStockItems() throws Exception {

    int pageno = 1;

    Log.info("开始取一号店仓库商品资料");
    String sql =
        "select orgid from ecs_tradecontactorgcontrast with(nolock) where tradecontactid="
            + tradecontactid;
    int orgid = this.getDao().intSelect(sql);
    for (int k = 0; k < 10; ) {
      try {

        while (true) {
          Map<String, String> productparams = new HashMap<String, String>();
          // 系统级参数设置
          productparams.put("appKey", app_key);
          productparams.put("sessionKey", token);
          productparams.put("format", format);
          productparams.put("method", "yhd.serial.products.search");
          productparams.put("ver", ver);
          productparams.put("timestamp", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));

          productparams.put("canShow", "1");
          productparams.put("canSale", "0");
          productparams.put("curPage", String.valueOf(pageno));
          productparams.put("pageRows", "20");
          productparams.put("verifyFlg", "2");

          String responseProductData = Utils.sendByPost(productparams, app_secret, url, "");
          Log.info("取仓库商品返回数据: " + responseProductData);

          JSONObject responseproduct = new JSONObject(responseProductData);

          int totalCount = responseproduct.getJSONObject("response").getInt("totalCount");

          JSONArray productlist =
              responseproduct
                  .getJSONObject("response")
                  .getJSONObject("serialProductList")
                  .getJSONArray("serialProduct");

          for (int i = 0; i < productlist.length(); i++) {
            JSONObject product = productlist.getJSONObject(i);

            long productId = product.optLong("productId");
            String productCode = product.optString("productCode");
            String productCname = product.optString("productCname");

            Log.info("货号:" + productCode + ",产品名称:" + productCname);

            StockManager.stockConfig(
                this.getDao(),
                orgid,
                Integer.valueOf(tradecontactid),
                String.valueOf(productId),
                productCode,
                productCname,
                0);

            Map<String, String> stockparams = new HashMap<String, String>();
            // 系统级参数设置
            stockparams.put("appKey", app_key);
            stockparams.put("sessionKey", token);
            stockparams.put("format", format);
            stockparams.put("method", "yhd.serial.product.get");
            stockparams.put("ver", ver);
            stockparams.put("timestamp", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));

            stockparams.put("productId", String.valueOf(productId));

            String responseData = Utils.sendByPost(stockparams, app_secret, url, "");
            Log.info("取仓库商品详情返回数据: " + responseData);
            JSONObject responsestock = new JSONObject(responseData);

            JSONArray childseriallist =
                responsestock
                    .getJSONObject("response")
                    .getJSONObject("serialChildProdList")
                    .getJSONArray("serialChildProd");

            for (int m = 0; m < childseriallist.length(); m++) {
              JSONObject childserial = childseriallist.optJSONObject(m);

              String sku = childserial.optString("outerId");
              long skuid = childserial.optLong("productId");

              JSONArray stocklist =
                  childserial.getJSONObject("allWareHouseStocList").getJSONArray("pmStockInfo");

              for (int j = 0; j < stocklist.length(); j++) {
                JSONObject stock = stocklist.optJSONObject(j);

                int quantity = stock.optInt("vs");
                long warehouseId = stock.optLong("warehouseId");

                StockManager.addStockConfigSku(
                    this.getDao(),
                    Integer.valueOf(tradecontactid),
                    String.valueOf(productId),
                    String.valueOf(skuid) + "-" + String.valueOf(warehouseId),
                    sku,
                    quantity);
              }
            }
          }

          // 判断是否有下一页
          if (pageno == (Double.valueOf(Math.ceil(totalCount / 20.0))).intValue()) break;

          pageno++;
        }

        break;

      } catch (Exception e) {
        if (++k >= 10) throw e;
        Log.warn(jobName + ", 远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));

        Thread.sleep(10000L);
      }
    }
  }
  @Override
  public void run() {
    Properties prop = StringUtil.getStringProperties(this.getExecuteobj().getParams());
    pageSize = prop.getProperty("pageSize");
    url = prop.getProperty("url");
    tradecontactid = prop.getProperty("tradecontactid");
    username = prop.getProperty("username");

    try {
      // 检查未入订单
      updateJobFlag(1);
      checkWaitStockOutOrders();
      // 检查取消订单
      checkCancleOrders();

      UpdateTimerJob();

      Log.info(
          jobName,
          "执行作业成功 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] 下次处理时间: "
              + this.datetimeformat.format(this.getExecuteobj().getNextactive()));

    } catch (Exception e) {
      try {

        if (this.getExecuteobj().getSkip() == 1) {
          UpdateTimerJob();
        } else UpdateTimerJob(Log.getErrorMessage(e));

        updateJobFlag(0);

        if (this.getConnection() != null && !this.getConnection().getAutoCommit())
          this.getConnection().rollback();

        if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
          this.getExtconnection().rollback();

      } catch (Exception e1) {
        Log.error(jobName, "回滚事务失败");
      }
      Log.error(jobName, "错误信息:" + Log.getErrorMessage(e));

      Log.error(
          jobName,
          "执行作业失败 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] \r\n  "
              + Log.getErrorMessage(e));

    } finally {
      try {
        updateJobFlag(0);
      } catch (Exception e) {
        Log.error(jobName, "更新处理标志失败");
      }

      try {
        if (this.getConnection() != null) this.getConnection().close();
        if (this.getExtconnection() != null) this.getExtconnection().close();

      } catch (Exception e) {
        Log.error(jobName, "关闭数据库连接失败");
      }
    }
  }
  // 检查取消订单  4 取消
  private void checkCancleOrders() throws Exception {
    int pageIndex = 1;
    boolean hasNextPage = true;

    for (int k = 0; k < 10; ) {
      try {
        int n = 1;

        while (hasNextPage) {
          Date enddate = new Date();
          Date startdate = new Date(new Date().getTime() - daymillis);
          // 方法名
          String apimethod = "search_order_list";
          HashMap<String, Object> reqMap = new HashMap<String, Object>();
          reqMap.put("last_modify_st_time", startdate.getTime() / 1000L);
          reqMap.put("last_modify_en_time", enddate.getTime() / 1000L);
          reqMap.put("pages", String.valueOf(pageIndex));
          reqMap.put("counts", pageSize);
          reqMap.put("return_data", "json");
          reqMap.put("act", apimethod);
          reqMap.put("api_version", "1.0");

          Log.info("第" + pageIndex + "页");
          String responseText = CommHelper.doRequest(reqMap, url);
          Log.info("返回数据为: " + responseText);
          // 把返回的数据转成json对象
          JSONObject responseObj = new JSONObject(responseText);
          // sn_error
          if (!"success".equals(responseObj.getString("result"))) { // 发生错误
            String operCode = responseObj.getJSONObject("sn_error").getString("error_code");
            if ("biz.handler.data-get:no-result".equals(operCode)) { // 没有结果
              Log.info("没有可用的订单!");
            } else {
              Log.warn("取订单出错了,错误码: " + operCode);
            }

            break;
          }

          JSONObject orderInfos = responseObj.getJSONObject("info");
          // 总页数
          String orderTotal = String.valueOf(orderInfos.getString("counts"));
          int orderTotaltemp = Integer.parseInt(orderTotal);
          int pageTotalTemp =
              orderTotaltemp < Integer.parseInt(pageSize)
                  ? 1
                  : orderTotaltemp / Integer.parseInt(pageSize) == 0
                      ? Integer.parseInt(pageSize)
                      : orderTotaltemp / Integer.parseInt(pageSize) + 1;
          String pageTotal = String.valueOf(pageTotalTemp);
          Log.info("总订单数为: " + orderTotal);
          Log.info("总页数为: " + pageTotal);
          if (orderTotal == null || orderTotal.equals("") || orderTotal.equals("0")) {
            break;
          }
          // 订单元素
          JSONArray ordersList = orderInfos.getJSONArray("data_info");
          for (int i = 0; i < ordersList.length(); i++) { // 某个订单
            JSONObject orderInfo = ordersList.getJSONObject(i);
            int returnOrderCount = 0;
            // 订单编号
            String orderCode = (String) orderInfo.get("order_sn");
            if (orderInfo.isNull("shop_info")) continue;
            // 订单商品集合
            JSONArray items = orderInfo.getJSONArray("shop_info");
            // 构造一个订单对象
            Order o = new Order();
            o.setObjValue(o, orderInfo);
            o.setFieldValue(o, "shop_info", items);
            Log.info("发货状态: " + o.getShipping_status() + "付款状态: " + o.getPay_status());
            if (o != null) {
              if ("4".equals(o.getPay_status())) { // 正常订单
                Log.info("订单号: " + o.getOrder_sn());
                // 如果是等待发货订单,创建接口订单成功,减少其它店的库存

                try {
                  OrderUtils.createInterOrder(
                      this.getDao().getConnection(), o, tradecontactid, username);

                } catch (SQLException sqle) {
                  throw new JException("生成退货订单出错!" + sqle.getMessage());
                }
              }
            }
          }
          // 判断是否有下一页
          if ("".equals(pageTotal) || pageTotal == null) pageTotal = "0";
          if (pageIndex >= Integer.parseInt(pageTotal)) hasNextPage = false;
          else pageIndex++;

          n++;
        }
        break;
      } catch (Exception e) {
        e.printStackTrace();
        if (++k >= 10) throw e;
        if (this.getDao() != null && !this.getDao().getConnection().getAutoCommit()) {
          this.getDao().rollback();
        }
        Log.warn(jobName + " ,远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
    Log.info("本次取ecshop退货订单任务处理完毕!");
  }
  /** 检查未入待发货订单 orderStatus=10 等待发货 这里检查一天时间的未入订单 */
  public void checkWaitStockOutOrders() throws Exception {
    Log.info(jobName + "任务开始!");
    Connection conn = this.getDao().getConnection();
    int pageIndex = 1;
    boolean hasNextPage = true;

    for (int k = 0; k < 5; ) {
      try {

        while (hasNextPage) {
          Date startdate = new Date(new Date().getTime() - daymillis);
          Date enddate = new Date();
          // 方法名
          String apimethod = "search_order_list";
          HashMap<String, Object> reqMap = new HashMap<String, Object>();
          reqMap.put("last_modify_st_time", startdate.getTime() / 1000L);
          reqMap.put("last_modify_en_time", enddate.getTime() / 1000L);
          reqMap.put("pages", String.valueOf(pageIndex));
          reqMap.put("counts", pageSize);
          reqMap.put("return_data", "json");
          reqMap.put("act", apimethod);
          reqMap.put("api_version", "1.0");
          // 发送请求

          Log.info("第" + pageIndex + "页");
          String responseText = CommHelper.doRequest(reqMap, url);
          Log.info("返回数据为: " + responseText);
          // 把返回的数据转成json对象
          JSONObject responseObj = new JSONObject(responseText.replaceAll(":null", ":\"\""));
          // 错误对象
          if (!"success".equals(responseObj.getString("result"))) { // 发生错误
            String operCode = responseObj.getJSONObject("sn_error").getString("error_code");
            if (operCode.indexOf("no-result") != -1) { // 没有数据直接退出方法体
              Log.error("获取ecshop订单列表", "获取订单列表失败,操作码:" + operCode);
              return;
            }
            hasNextPage = false;
            break;
          }

          JSONObject orderInfos = responseObj.getJSONObject("info");
          String orderTotal = String.valueOf(orderInfos.getString("counts"));
          int orderTotaltemp = Integer.parseInt(orderTotal);
          int pageTotalTemp =
              Double.valueOf(Math.ceil(orderTotaltemp / Double.parseDouble(Params.pageSize)))
                  .intValue();
          String pageTotal = String.valueOf(pageTotalTemp);

          Log.info("总订单数为: " + orderTotal);
          Log.info("总页数为: " + pageTotal);
          if (orderTotal == null || orderTotal.equals("") || orderTotal.equals("0")) {
            break;
          }
          // 订单元素
          JSONArray ordersList = orderInfos.getJSONArray("data_info");
          for (int i = 0; i < ordersList.length(); i++) { // 某个订单
            JSONObject orderInfo = ordersList.getJSONObject(i);
            // 订单编号
            String orderCode = (String) orderInfo.get("order_sn");
            if (orderInfo.isNull("shop_info")) continue;
            // 订单商品集合
            JSONArray items = orderInfo.getJSONArray("shop_info");
            // 构造一个订单对象
            Order o = new Order();
            o.setObjValue(o, orderInfo);
            o.setFieldValue(o, "shop_info", items);
            Log.info(
                "订单号: "
                    + o.getOrder_sn()
                    + ", 发货状态: "
                    + o.getShipping_status()
                    + "付款状态: "
                    + o.getPay_status());
            if (o != null) {
              if ("0".equals(o.getShipping_status()) && "2".equals(o.getPay_status())) { // 正常订单
                Log.info("检查到一条订单:" + orderCode);
                // 如果是等待发货订单,创建接口订单成功,减少其它店的库存
                if (!OrderManager.isCheck(jobName, conn, orderCode)) {
                  if (!OrderManager.TidLastModifyIntfExists(
                      jobName, conn, orderCode, new Date(o.getAdd_time() * 1000L))) {
                    try {
                      OrderUtils.createInterOrder(conn, o, tradecontactid, username);
                      for (Iterator ito = o.getShop_info().getRelationData().iterator();
                          ito.hasNext(); ) {
                        OrderItem item = (OrderItem) ito.next();
                        String sku = item.getProduct_sn();
                        StockManager.deleteWaitPayStock(
                            jobName, conn, tradecontactid, orderCode, sku);
                        long qty = (long) item.getGoods_number();
                        // 在ecs_rationconfig表中存在机构添加一条库存同步记录(不包括自己)
                        StockManager.addSynReduceStore(
                            jobName, conn, tradecontactid, "未发货", o.getOrder_sn(), sku, qty, false);
                      }

                    } catch (SQLException sqle) {
                      throw new JException("生成接口订单出错!" + sqle.getMessage());
                    }
                  }
                } // 订单状态 10待发货,20已发货,21部分发货,30交易成功 ,40交易关闭
              }
            }
          }
          // 判断是否有下一页
          if ("".equals(pageTotal) || pageTotal == null) pageTotal = "0";
          if (pageIndex >= Integer.parseInt(pageTotal)) hasNextPage = false;
          else pageIndex++;

          break;
        }
        Log.info(jobName + "执行完毕!");
        break;
      } catch (Exception e) {
        if (++k >= 5) throw e;
        if (conn != null && !conn.getAutoCommit()) {
          conn.rollback();
        }
        Log.warn(jobName + " ,远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
  }
  public void run() {
    Properties proper = StringUtil.getStringProperties(this.getExecuteobj().getParams());
    tid = proper.getProperty("tid");
    tradecontactid = proper.getProperty("tradecontactid");
    url = proper.getProperty("url");
    appkey = proper.getProperty("appkey");
    appsecret = proper.getProperty("appsecret");
    authcode = proper.getProperty("authcode");
    sellernick = proper.getProperty("sellernick");
    try {
      updateJobFlag(1);
      String sql = "select isnull(value,0) from config where name='等待付款订单是否进系统'";
      if ("1".equals(this.getDao().strSelect(sql))) ;
      waitbuyerpayisin = true;

      TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret, "xml");
      TradeGetRequest req = new TradeGetRequest();
      req.setFields("tid,modified,status,orders.outer_sku_id,orders.num");
      req.setTid(Long.parseLong(tid));
      TradeGetResponse response = client.execute(req, authcode);

      if (response.getTrade() == null) {
        return;
      }

      Trade td = response.getTrade();

      if (td.getStatus().equals("WAIT_SELLER_SEND_GOODS")) {

        if (!OrderManager.isCheck(
            "检查淘宝订单", this.getDao().getConnection(), String.valueOf(td.getTid()))) {
          if (!OrderManager.TidLastModifyIntfExists(
              "检查淘宝订单",
              this.getDao().getConnection(),
              String.valueOf(td.getTid()),
              td.getModified())) {
            OrderUtils.createInterOrder(
                this.getDao().getConnection(), td, Params.tradecontactid, Params.username, true);
            for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
              Order o = (Order) ito.next();
              String sku = o.getOuterSkuId();

              StockManager.deleteWaitPayStock(
                  jobName,
                  this.getDao().getConnection(),
                  Params.tradecontactid,
                  String.valueOf(td.getTid()),
                  sku);
              StockManager.addSynReduceStore(
                  jobName,
                  this.getDao().getConnection(),
                  Params.tradecontactid,
                  td.getStatus(),
                  String.valueOf(td.getTid()),
                  sku,
                  -o.getNum(),
                  false);
            }
          }
        }

        // 等待买家付款时记录锁定库存
      } else if (td.getStatus().equals("WAIT_BUYER_PAY")
          || td.getStatus().equals("TRADE_NO_CREATE_PAY")) {
        if (waitbuyerpayisin) {
          if (!OrderManager.TidLastModifyIntfExists(
              "检查淘宝订单",
              this.getDao().getConnection(),
              String.valueOf(td.getTid()),
              td.getModified())) {
            OrderUtils.createInterOrder(
                this.getDao().getConnection(), td, Params.tradecontactid, Params.username, false);
          }
        }
        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();
          StockManager.addWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku,
              o.getNum());
          StockManager.addSynReduceStore(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              td.getStatus(),
              String.valueOf(td.getTid()),
              sku,
              -o.getNum(),
              false);
        }

        // 付款以后用户退款成功,交易自动关闭
        // 释放库存,数量为负数
      } else if (td.getStatus().equals("TRADE_CLOSED")) {
        OrderManager.CancelOrderByCID(
            jobName, this.getDao().getConnection(), String.valueOf(td.getTid()));
        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();
          StockManager.deleteWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku);
          // StockManager.addSynReduceStore(jobName, this.getDao().getConnection(),
          // Params.tradecontactid, td.getStatus(),String.valueOf(td.getTid()),sku,
          // o.getNum(),false);
        }

        // 付款以前,卖家或买家主动关闭交易
        // 释放等待买家付款时锁定的库存
      } else if (td.getStatus().equals("TRADE_CLOSED_BY_TAOBAO")) {

        if (waitbuyerpayisin) {

          if (!OrderManager.TidLastModifyIntfExists(
              "检查淘宝订单",
              this.getDao().getConnection(),
              String.valueOf(td.getTid()),
              td.getModified())) {
            OrderUtils.createInterOrder(
                this.getDao().getConnection(), td, Params.tradecontactid, Params.username, false);
          }
        }

        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();

          StockManager.deleteWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku);

          if (StockManager.WaitPayStockExists(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku)) // 有获取到等待买家付款状态时才加库存
          {

            StockManager.addSynReduceStore(
                jobName,
                this.getDao().getConnection(),
                Params.tradecontactid,
                td.getStatus(),
                String.valueOf(td.getTid()),
                sku,
                o.getNum(),
                false);
          }
        }

      } else if (td.getStatus().equals("TRADE_FINISHED")) {

        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();

          StockManager.deleteWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku);

          // 更新结束时间

          OrderUtils.updateFinishedStatus(
              this.getDao().getConnection(), Params.tradecontactid, td.getTid(), td.getEndTime());
        }
      }

      // if(Params.isc)
      // {
      // 处理退货
      for (Iterator oit = td.getOrders().iterator(); oit.hasNext(); ) {
        Order o = (Order) oit.next();
        // Log.info("订单号:"+String.valueOf(td.getTid())+" 退货ID:"+String.valueOf(o.getRefundId()));
        if (o.getRefundId() > 0) {
          OrderUtils.getRefund(
              jobName,
              this.getDao().getConnection(),
              Params.url,
              Params.appkey,
              Params.appsecret,
              Params.authcode,
              Params.tradecontactid,
              td,
              o,
              String.valueOf(td.getTid()),
              o.getRefundId());
        }
      }

      updateJobFlag(0);
      Log.info(
          jobName,
          "执行作业成功 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] 下次处理时间: "
              + this.datetimeformat.format(this.getExecuteobj().getNextactive()));

    } catch (Exception e) {
      try {

        if (this.getDao().getConnection() != null
            && !this.getDao().getConnection().getAutoCommit()) {
          this.getDao().getConnection().rollback();
          this.getDao().getConnection().setAutoCommit(true);
        }

      } catch (Exception e1) {
        Log.error(jobName, "回滚事务失败");
        Log.error(jobName, e1.getMessage());
      }

      try {
        if (this.getExecuteobj().getSkip() == 1) {
          UpdateTimerJob();
        } else UpdateTimerJob(Log.getErrorMessage(e));
      } catch (Exception ex) {
        Log.error(jobName, "更新任务信息失败");
        Log.error(jobName, ex.getMessage());
      }
      Log.error(jobName, "错误信息:" + Log.getErrorMessage(e));

      Log.error(
          jobName,
          "执行作业失败 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] \r\n  "
              + Log.getErrorMessage(e));
    } finally {

      try {
        updateJobFlag(0);
      } catch (Exception e) {
        Log.error(jobName, e.getMessage());
        Log.error(jobName, "更新处理标志失败");
        TimerRunner.modifiedErrVect(this.getExecuteobj().getId());
      }

      try {
        if (this.getDao().getConnection() != null) {
          this.getDao().getConnection().setAutoCommit(true);
          this.getDao().getConnection().close();
        }

      } catch (Exception e) {
        Log.error(jobName, "关闭数据库连接失败");
      }
    }
  }
Beispiel #13
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");

    do {
      Connection conn = null;
      try {
        conn = PoolHelper.getInstance().getConnection(Params.dbname);
        List infsheetlist = JwUtil.getintfsheetlist(conn, 900000, 100);
        Order order = null;
        for (Iterator it = infsheetlist.iterator(); it.hasNext(); ) {
          try {
            Hashtable ht = (Hashtable) it.next();
            Integer serialID = (Integer) ht.get("SerialID");
            String operData = (String) ht.get("OperData");
            String sql =
                "SELECT * from Inf_downNotebak where operdata='"
                    + operData
                    + "' AND SheetType='900000' AND result='success' and opertype='100'";
            Vector duplicateNum = SQLHelper.multiRowSelect(conn, sql);
            if (duplicateNum != null && duplicateNum.size() > 0) {
              conn.setAutoCommit(false);
              JwUtil.delBackUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("此单已发送,删除重复的单成功,订单号: " + order.getOrderCode());
              continue;
            }
            sql =
                "select a.custompursheetid orderCode,a.custompursheetid orderDetailCode,a.tax "
                    + "orderTax,convert(varchar,a.notifydate,20) createDate,convert(varchar,a.notifydate,20) "
                    + "updateDate,convert(varchar,a.notifydate,20) payTime,a.postfee postPrice,a.CustomsOrderNo "
                    + "invoiceName,a.note buyerMessage,a.payfee amountReceivable,a.payfee actualPayment,"
                    + "a.linkman name, a.tele mobilePhone,a.address,isnull(a.zipcode,'000000') zip,b.notifyqty num,"
                    + "b.title,b.price,  b.price*b.notifyqty payment,b.price*b.notifyqty totalPrice,"
                    + "c.custombc skuID ,rtrim(c.outerSkuId) outerSkuId,a.customsbarcode hgBarcode "
                    + "from outstock0 a with(nolock),outstockitem0 b with(nolock),barcode c with(nolock) where a.sheetid=b.sheetid and b.barcodeid=c.barcodeid and a.sheetid='"
                    + operData
                    + "'";
            Vector sqlresult = SQLHelper.multiRowSelect(conn, sql);
            if (sqlresult.size() == 0) {
              conn.setAutoCommit(false);
              JwUtil.backUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("同步订单失败,订单已经处理或不存在,订单号: " + order.getOrderCode());
              continue;
            }

            order = new Order();
            ReceiveInfo receiveInfo = new ReceiveInfo();
            int i = 0;
            detail det = null;
            for (Iterator t = sqlresult.iterator(); t.hasNext(); ) {
              Hashtable htTemp = (Hashtable) t.next();
              if (i == 0) {
                order.getMapData(htTemp);
                receiveInfo.getMapData(htTemp);
                String address = receiveInfo.getAddress();
                if (address.indexOf(" ") > 0) {
                  String[] add = address.split(" "); // 设置地址明细
                  if (add.length < 3) {
                    System.out.println(operData + " 地址不符合要求");
                  }
                  if (add.length == 4) {
                    receiveInfo.setProvince(add[0]);
                    receiveInfo.setCity(add[1]);
                    receiveInfo.setDistrict(add[2]);
                    receiveInfo.setAddress(add[3]);

                  } else if (add.length == 5) {
                    receiveInfo.setProvince(add[0]);
                    receiveInfo.setCity(add[1]);
                    receiveInfo.setDistrict(add[2]);
                    receiveInfo.setAddress(add[4].trim());
                  } else {
                    receiveInfo.setProvince(add[0]);
                    receiveInfo.setCity(add[1]);
                    receiveInfo.setDistrict(add[2]);
                  }
                }
                String mobilePhone = receiveInfo.getMobilePhone();
                mobilePhone = mobilePhone.replaceAll(" +", " ");
                if (mobilePhone.indexOf(" ") > 0) {
                  String[] contacts = mobilePhone.split(" ");
                  receiveInfo.setMobilephone(contacts[0]);
                  if (contacts[1].length() == 11) // 如果是手机号码就设置,如果是身份证就不设置了
                  receiveInfo.setPhone(contacts[1]);
                } else if (mobilePhone.indexOf("/") > 0) {
                  String[] contacts = mobilePhone.split("/");
                  if (contacts.length == 2) {
                    receiveInfo.setMobilephone(contacts[0]);
                    if (contacts[1].length() == 11) // 如果是手机号码就设置,如果是身份证就不设置了
                    receiveInfo.setPhone(contacts[1]);
                  }
                } else {
                  receiveInfo.setMobilephone(mobilePhone);
                }
              }
              det = new detail();
              det.getMapData(htTemp);
              order.getDetail().getRelationData().add(det);
              i++;
            }
            // Log.info("address: "+receiveInfo.getAddress());
            order.setReceiver(receiveInfo.toJSONObject());
            String temp = order.toJSONObject().replaceAll("\"\\{", "\\{");
            temp = temp.replaceAll("\",\"detail\"", ",\"detail\"");
            // Log.info("temp: "+temp);
            String bizData1 = "{\"saleOrderList\":[" + temp + "]}";
            String sign = JwUtil.makeSign(bizData1);
            Map requestParams =
                JwUtil.makeRequestParams(bizData1, service, Params.appkey, Params.format, sign);
            String result = CommHelper.sendRequest(Params.url, requestParams, "");
            Log.info("result: " + result);
            JSONObject re = new JSONObject(result);
            if (re.getBoolean("isSuccess")) {
              conn.setAutoCommit(false);
              JwUtil.backUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("同步订单成功,订单号: " + order.getOrderCode());

            } else if (re.getString("body").contains("推送订单错误,可能已存在")) {
              conn.setAutoCommit(false);
              JwUtil.delBackUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("删除重复的单成功,订单号: " + order.getOrderCode());
            } else {
              Log.error(jobname, "sheetid: " + operData + " " + re.getString("body"));
            }
          } catch (Exception e) {
            Log.error(jobname, e.getMessage());
            if (conn != null && !conn.getAutoCommit()) conn.rollback();
            continue;
          }
        }
      } catch (Exception e) {
        try {
          if (conn != null && !conn.getAutoCommit()) conn.rollback();
        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        try {
          if (conn != null) conn.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime < (long) (Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Beispiel #14
0
  /*
   * 获取一天之类的退款订单
   */
  private void getRefundBillList(Connection conn) throws Exception {
    long pageno = 1L;
    Date modified = Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT);
    for (int k = 0; k < 10; ) {
      try {
        TaobaoClient client =
            new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret, "json");
        TmallEaiOrderRefundMgetRequest req = new TmallEaiOrderRefundMgetRequest();
        Date startdate =
            new Date(Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT).getTime() + 1000L);
        Date enddate =
            new Date(
                Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT).getTime() + daymillis);
        req.setStartTime(startdate);
        req.setEndTime(enddate);
        req.setPageNo(pageno);
        req.setPageSize(40L);
        req.setUseHasNext(true);
        TmallEaiOrderRefundMgetResponse response = client.execute(req, Params.authcode);

        while (true) {
          if (response.getRefundBillList() == null || response.getRefundBillList().size() <= 0) {
            if (pageno == 1) {
              try {
                // 如一天之内都取不到订单,而且当前天大于配置天,则将取订单最新时间更新为当前天的零点
                if (this.dateformat
                        .parse(Formatter.format(new Date(), Formatter.DATE_FORMAT))
                        .compareTo(
                            this.dateformat.parse(
                                Formatter.format(
                                    Formatter.parseDate(
                                        PublicUtils.getConfig(conn, lasttimeconfvalue, ""),
                                        Formatter.DATE_TIME_FORMAT),
                                    Formatter.DATE_FORMAT)))
                    > 0) {
                  try {
                    String value =
                        Formatter.format(
                                (new Date(
                                    Formatter.parseDate(
                                                PublicUtils.getConfig(conn, lasttimeconfvalue, ""),
                                                Formatter.DATE_TIME_FORMAT)
                                            .getTime()
                                        + daymillis)),
                                Formatter.DATE_FORMAT)
                            + " 00:00:00";
                    PublicUtils.setConfig(conn, lasttimeconfvalue, value);
                  } catch (JException je) {
                    Log.error(jobname, je.getMessage());
                  }
                }
              } catch (ParseException e) {
                Log.error(jobname, "不可用的日期格式!" + e.getMessage());
              }
            }
            break;
          }

          for (Iterator it = response.getRefundBillList().iterator(); it.hasNext(); ) {
            RefundBill refundbill = (RefundBill) it.next();

            Log.info(
                refundbill.getTid()
                    + " "
                    + refundbill.getStatus()
                    + " "
                    + refundbill.getModified());

            if (!RefundUtil.RefundBillisCheck(
                conn,
                String.valueOf(refundbill.getTid()),
                String.valueOf(refundbill.getRefundId()),
                refundbill.getModified())) {
              Trade td =
                  OrderUtils.getFullTrade(
                      String.valueOf(refundbill.getTid()),
                      Params.url,
                      Params.address,
                      Params.appsecret,
                      Params.authcode);

              RefundUtil.createRefundBill(conn, refundbill, td, Params.tradecontactid);
            }
            if (Formatter.parseDate(refundbill.getModified(), Formatter.DATE_TIME_FORMAT)
                    .compareTo(modified)
                > 0) {
              modified = Formatter.parseDate(refundbill.getModified(), Formatter.DATE_TIME_FORMAT);
            }
          }

          // 判断是否下一页
          if (response.getHasNext()) {
            pageno++;
          } else {
            break;
          }
        }
        if (modified.compareTo(Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT)) > 0) {
          try {
            String value = Formatter.format(modified, Formatter.DATE_TIME_FORMAT);
            PublicUtils.setConfig(conn, lasttimeconfvalue, value);
          } catch (JException je) {
            Log.error(jobname, je.getMessage());
          }
        }
        // 执行成功后不再循环
        break;
      } catch (Exception e) {
        if (++k >= 10) throw e;
        Log.warn("远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
  }