Beispiel #1
0
  /**
   * Update the SQL string and replace the ? markers with parameter names eg @P0, @P1 etc.
   *
   * @param sql the SQL containing markers to substitute
   * @param list the parameter list
   * @return the modified SQL as a <code>String</code>
   */
  static String substituteParamMarkers(String sql, ParamInfo[] list) {
    // A parameter can have at most 8 characters: " @P" plus at most 4
    // digits plus " ". We subtract the "?" placeholder, that's at most
    // 7 extra characters needed for each parameter.
    char[] buf = new char[sql.length() + list.length * 7];
    int bufferPtr = 0; // Output buffer pointer
    int start = 0; // Input string pointer
    StringBuffer number = new StringBuffer(4);

    for (int i = 0; i < list.length; i++) {
      int pos = list[i].markerPos;

      if (pos > 0) {
        sql.getChars(start, pos, buf, bufferPtr);
        bufferPtr += (pos - start);
        start = pos + 1;

        // Append " @P"
        buf[bufferPtr++] = ' ';
        buf[bufferPtr++] = '@';
        buf[bufferPtr++] = 'P';

        // Append parameter number
        // Rather complicated, but it's the only way in which no
        // unnecessary objects are created
        number.setLength(0);
        number.append(i);
        number.getChars(0, number.length(), buf, bufferPtr);
        bufferPtr += number.length();

        // Append " "
        buf[bufferPtr++] = ' ';
      }
    }

    if (start < sql.length()) {
      sql.getChars(start, sql.length(), buf, bufferPtr);
      bufferPtr += (sql.length() - start);
    }

    return new String(buf, 0, bufferPtr);
  }
  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @param pageNo 页号
   * @param rowsPerPage 每页的行数
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions, int pageNo, int rowsPerPage)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("LineCode,");
    buffer.append("StatMonth,");
    buffer.append("PowerClass,");
    buffer.append("ElectricQuantity,");
    buffer.append("PointerQuantity,");
    buffer.append("SanXiaFee,");
    buffer.append("Surcharge,");
    buffer.append("SumFee,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("TransLoss,");
    buffer.append("LineLoss,");
    buffer.append("UnPointerQuantity,");
    buffer.append("RateCode,");
    buffer.append("AdjustRate,");
    buffer.append("FarmUseScale,");
    buffer.append("FarmUsePrice,");
    buffer.append("FarmUseQuantity,");
    buffer.append("FarmUseFee,");
    buffer.append("ProductScale,");
    buffer.append("ProductPrice,");
    buffer.append("ProductQuantity,");
    buffer.append("ProductFee,");
    buffer.append("DenizenScale,");
    buffer.append("DenizenPrice,");
    buffer.append("DenizenQuantity,");
    buffer.append("DenizenFee,");
    buffer.append("UnDenizenScale,");
    buffer.append("UnDenizenPrice,");
    buffer.append("UnDenizenQuantity,");
    buffer.append("UnDenizenFee,");
    buffer.append("IndustryScale,");
    buffer.append("IndustryPrice,");
    buffer.append("IndustryQuantity,");
    buffer.append("IndustryFee,");
    buffer.append("BizScale,");
    buffer.append("BizPrice,");
    buffer.append("BizQuantity,");
    buffer.append("BizFee,");
    buffer.append("PowerRateFee,");
    buffer.append("UpCompany,");
    buffer.append("PowerFee,");
    buffer.append("InputDate,");
    buffer.append("Kv,");
    buffer.append("Wholesaletype,");
    buffer.append("WorkNum,");
    buffer.append("UnWorkNum,");
    buffer.append("OtherSurcharge,");
    buffer.append("DifferenceQuantity,");
    buffer.append("UnTransLoss,");
    buffer.append("UnLineLoss ");
    buffer.append("FROM LwWholeSaleSummary WHERE ");
    buffer.append(conditions);
    boolean supportPaging = false; // 数据库是否支持分页
    if (pageNo > 0) {
      // 对Oracle优化
      if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("Oracle")) {
        buffer.insert(0, "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (");
        buffer.append(
            ") row_ WHERE rownum <= "
                + rowsPerPage * pageNo
                + ") WHERE rownum_ > "
                + rowsPerPage * (pageNo - 1));
        supportPaging = true;
      } else if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("DB2")) {
        String sql = buffer.toString();
        buffer.setLength(0);
        buffer.append("select * from ( select rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) {
          buffer.append(sql.substring(orderByIndex));
        }
        buffer.append(") as rownumber_,");
        buffer.append(sql.substring(6));
        buffer.append(" ) as temp_ where rownumber_");
        buffer.append(
            " between " + (rowsPerPage * (pageNo - 1) + 1) + " and " + rowsPerPage * pageNo);
        supportPaging = true;
      }
    }
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    ResultSet resultSet = dbManager.executeQuery(buffer.toString());
    int count = 0;
    if (supportPaging == false && pageNo > 1) {
      dbManager.locate(resultSet, rowsPerPage * (pageNo - 1));
    }

    // 定义返回结果集合
    Collection collection = new ArrayList(rowsPerPage);
    LwWholeSaleSummaryDto lwWholeSaleSummaryDto = null;
    while (resultSet.next()) {
      if (supportPaging == false && pageNo > 0) {
        count++;
        if (count > rowsPerPage) {
          break;
        }
      }

      lwWholeSaleSummaryDto = new LwWholeSaleSummaryDto();
      lwWholeSaleSummaryDto.setLineCode(dbManager.getString(resultSet, "LineCode"));
      lwWholeSaleSummaryDto.setStatMonth(dbManager.getString(resultSet, "StatMonth"));
      lwWholeSaleSummaryDto.setPowerClass(dbManager.getString(resultSet, "PowerClass"));
      lwWholeSaleSummaryDto.setElectricQuantity(dbManager.getDouble(resultSet, "ElectricQuantity"));
      lwWholeSaleSummaryDto.setPointerQuantity(dbManager.getDouble(resultSet, "PointerQuantity"));
      lwWholeSaleSummaryDto.setSanXiaFee(dbManager.getDouble(resultSet, "SanXiaFee"));
      lwWholeSaleSummaryDto.setSurcharge(dbManager.getDouble(resultSet, "Surcharge"));
      lwWholeSaleSummaryDto.setSumFee(dbManager.getDouble(resultSet, "SumFee"));
      lwWholeSaleSummaryDto.setValidStatus(dbManager.getString(resultSet, "ValidStatus"));
      lwWholeSaleSummaryDto.setFlag(dbManager.getString(resultSet, "Flag"));
      lwWholeSaleSummaryDto.setRemark(dbManager.getString(resultSet, "Remark"));
      lwWholeSaleSummaryDto.setTransLoss(dbManager.getDouble(resultSet, "TransLoss"));
      lwWholeSaleSummaryDto.setLineLoss(dbManager.getDouble(resultSet, "LineLoss"));
      lwWholeSaleSummaryDto.setUnPointerQuantity(
          dbManager.getDouble(resultSet, "UnPointerQuantity"));
      lwWholeSaleSummaryDto.setRateCode(dbManager.getDouble(resultSet, "RateCode"));
      lwWholeSaleSummaryDto.setAdjustRate(dbManager.getDouble(resultSet, "AdjustRate"));
      lwWholeSaleSummaryDto.setFarmUseScale(dbManager.getDouble(resultSet, "FarmUseScale"));
      lwWholeSaleSummaryDto.setFarmUsePrice(dbManager.getDouble(resultSet, "FarmUsePrice"));
      lwWholeSaleSummaryDto.setFarmUseQuantity(dbManager.getDouble(resultSet, "FarmUseQuantity"));
      lwWholeSaleSummaryDto.setFarmUseFee(dbManager.getDouble(resultSet, "FarmUseFee"));
      lwWholeSaleSummaryDto.setProductScale(dbManager.getDouble(resultSet, "ProductScale"));
      lwWholeSaleSummaryDto.setProductPrice(dbManager.getDouble(resultSet, "ProductPrice"));
      lwWholeSaleSummaryDto.setProductQuantity(dbManager.getDouble(resultSet, "ProductQuantity"));
      lwWholeSaleSummaryDto.setProductFee(dbManager.getDouble(resultSet, "ProductFee"));
      lwWholeSaleSummaryDto.setDenizenScale(dbManager.getDouble(resultSet, "DenizenScale"));
      lwWholeSaleSummaryDto.setDenizenPrice(dbManager.getDouble(resultSet, "DenizenPrice"));
      lwWholeSaleSummaryDto.setDenizenQuantity(dbManager.getDouble(resultSet, "DenizenQuantity"));
      lwWholeSaleSummaryDto.setDenizenFee(dbManager.getDouble(resultSet, "DenizenFee"));
      lwWholeSaleSummaryDto.setUnDenizenScale(dbManager.getDouble(resultSet, "UnDenizenScale"));
      lwWholeSaleSummaryDto.setUnDenizenPrice(dbManager.getDouble(resultSet, "UnDenizenPrice"));
      lwWholeSaleSummaryDto.setUnDenizenQuantity(
          dbManager.getDouble(resultSet, "UnDenizenQuantity"));
      lwWholeSaleSummaryDto.setUnDenizenFee(dbManager.getDouble(resultSet, "UnDenizenFee"));
      lwWholeSaleSummaryDto.setIndustryScale(dbManager.getDouble(resultSet, "IndustryScale"));
      lwWholeSaleSummaryDto.setIndustryPrice(dbManager.getDouble(resultSet, "IndustryPrice"));
      lwWholeSaleSummaryDto.setIndustryQuantity(dbManager.getDouble(resultSet, "IndustryQuantity"));
      lwWholeSaleSummaryDto.setIndustryFee(dbManager.getDouble(resultSet, "IndustryFee"));
      lwWholeSaleSummaryDto.setBizScale(dbManager.getDouble(resultSet, "BizScale"));
      lwWholeSaleSummaryDto.setBizPrice(dbManager.getDouble(resultSet, "BizPrice"));
      lwWholeSaleSummaryDto.setBizQuantity(dbManager.getDouble(resultSet, "BizQuantity"));
      lwWholeSaleSummaryDto.setBizFee(dbManager.getDouble(resultSet, "BizFee"));
      lwWholeSaleSummaryDto.setPowerRateFee(dbManager.getDouble(resultSet, "PowerRateFee"));
      lwWholeSaleSummaryDto.setUpCompany(dbManager.getString(resultSet, "UpCompany"));
      lwWholeSaleSummaryDto.setPowerFee(dbManager.getDouble(resultSet, "PowerFee"));
      lwWholeSaleSummaryDto.setInputDate(dbManager.getString(resultSet, "InputDate"));
      lwWholeSaleSummaryDto.setKv(dbManager.getString(resultSet, "Kv"));
      lwWholeSaleSummaryDto.setWholesaletype(dbManager.getString(resultSet, "Wholesaletype"));
      lwWholeSaleSummaryDto.setWorkNum(dbManager.getDouble(resultSet, "WorkNum"));
      lwWholeSaleSummaryDto.setUnWorkNum(dbManager.getDouble(resultSet, "UnWorkNum"));
      lwWholeSaleSummaryDto.setOtherSurcharge(dbManager.getDouble(resultSet, "OtherSurcharge"));
      lwWholeSaleSummaryDto.setDifferenceQuantity(
          dbManager.getString(resultSet, "DifferenceQuantity"));
      lwWholeSaleSummaryDto.setUnTransLoss(dbManager.getDouble(resultSet, "UnTransLoss"));
      lwWholeSaleSummaryDto.setUnLineLoss(dbManager.getDouble(resultSet, "UnLineLoss"));
      collection.add(lwWholeSaleSummaryDto);
    }
    resultSet.close();
    return collection;
  }
Beispiel #3
0
  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @param pageNo 页号
   * @param rowsPerPage 每页的行数
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions, int pageNo, int rowsPerPage)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("LineCode,");
    buffer.append("R,");
    buffer.append("LineLong,");
    buffer.append("Volt,");
    buffer.append("T,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark ");
    buffer.append("FROM LineLoss WHERE ");
    buffer.append(conditions);
    boolean supportPaging = false; // 数据库是否支持分页
    if (pageNo > 0) {
      // 对Oracle优化
      if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("Oracle")) {
        buffer.insert(0, "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (");
        buffer.append(
            ") row_ WHERE rownum <= "
                + rowsPerPage * pageNo
                + ") WHERE rownum_ > "
                + rowsPerPage * (pageNo - 1));
        supportPaging = true;
      } else if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("DB2")) {
        String sql = buffer.toString();
        buffer.setLength(0);
        buffer.append("select * from ( select rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) {
          buffer.append(sql.substring(orderByIndex));
        }
        buffer.append(") as rownumber_,");
        buffer.append(sql.substring(6));
        buffer.append(" ) as temp_ where rownumber_");
        buffer.append(
            " between " + (rowsPerPage * (pageNo - 1) + 1) + " and " + rowsPerPage * pageNo);
        supportPaging = true;
      }
    }
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    ResultSet resultSet = dbManager.executeQuery(buffer.toString());
    int count = 0;
    if (supportPaging == false && pageNo > 1) {
      dbManager.locate(resultSet, rowsPerPage * (pageNo - 1));
    }

    // 定义返回结果集合
    Collection collection = new ArrayList(rowsPerPage);
    LineLossDto lineLossDto = null;
    while (resultSet.next()) {
      if (supportPaging == false && pageNo > 0) {
        count++;
        if (count > rowsPerPage) {
          break;
        }
      }

      lineLossDto = new LineLossDto();
      lineLossDto.setLineCode(dbManager.getString(resultSet, "LineCode"));
      lineLossDto.setR(dbManager.getDouble(resultSet, "R"));
      lineLossDto.setLineLong(dbManager.getDouble(resultSet, "LineLong"));
      lineLossDto.setVolt(dbManager.getDouble(resultSet, "Volt"));
      lineLossDto.setT(dbManager.getDouble(resultSet, "T"));
      lineLossDto.setValidStatus(dbManager.getString(resultSet, "ValidStatus"));
      lineLossDto.setFlag(dbManager.getString(resultSet, "Flag"));
      lineLossDto.setRemark(dbManager.getString(resultSet, "Remark"));
      collection.add(lineLossDto);
    }
    resultSet.close();
    return collection;
  }
Beispiel #4
0
  // initiate either a server or a user session
  public void run() {
    if (isDaemon) {
      daemon();
      return;
    }
    ;

    boolean loggedIn = false;
    int i, h1;
    String di, str1, user = "******", user_id = "0";
    InetAddress localNode;
    byte dataBuffer[] = new byte[1024];
    String command = null;
    StringBuffer statusMessage = new StringBuffer(40);
    File targetFile = null;

    try {
      // start mysql
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      this.db_conn = DriverManager.getConnection(db_url);
      this.db_stmt = this.db_conn.createStatement();

      this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')");

      incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout
      remoteNode = incoming.getInetAddress();
      localNode = InetAddress.getLocalHost();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET));
      PrintWriter out =
          new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true);
      str1 = "220 Flickr FTP Server Ready";
      out.println(str1);
      if (log) System.out.println(remoteNode.getHostName() + " " + str1);

      boolean done = false;
      char dataType = 0;

      while (!done) {
        statusMessage.setLength(0);

        // obtain and tokenize command
        String str = in.readLine();
        if (str == null) break; // EOS reached
        i = str.indexOf(' ');
        if (i == -1) i = str.length();
        command = str.substring(0, i).toUpperCase().intern();
        if (log)
          System.out.print(
              user
                  + "@"
                  + remoteNode.getHostName()
                  + " "
                  + (String) ((command != "PASS") ? str : "PASS ***"));
        str = str.substring(i).trim();

        try {
          if (command == "USER") {

            user = str;
            statusMessage.append("331 Password");

          } else if (command == "PASS") {

            String pass = str;
            String pass_md5 = md5(pass);

            this.db_rs =
                this.db_stmt.executeQuery(
                    "SELECT * FROM users WHERE email='"
                        + user
                        + "' AND password='******'");
            if (this.db_rs.first()) {
              loggedIn = true;
              user_id = this.db_rs.getString("id");
              System.out.println("Account id is " + user_id);
            }

            statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect");

          } else if (!loggedIn) {

            statusMessage.append("530 Not logged in");

          } else if (command == "RETR") {

            statusMessage.append("999 Not likely");

          } else if (command == "STOR") {

            out.println(BINARY_XFER);

            // trim a leading slash off the filename if there is one
            if (str.substring(0, 1).equals("/")) str = str.substring(1);
            String filename = user_id + "_" + str;
            // TODO: sanitise filename
            targetFile = new File(upload_root + "/" + filename);

            RandomAccessFile dataFile = null;
            InputStream inStream = null;
            OutputStream outStream = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
              int amount;
              dataSocket = setupDataLink();

              // ensure timeout on reads.
              dataSocket.setSoTimeout(inactivityTimer);

              dataFile = new RandomAccessFile(targetFile, "rw");

              inStream = dataSocket.getInputStream();
              while ((amount = inStream.read(dataBuffer)) != -1)
                dataFile.write(dataBuffer, 0, amount);

              statusMessage.append(XFER_COMPLETE);

              shell_exec(ingest_path + " " + user_id + " " + filename);
            } finally {
              try {
                if (inStream != null) inStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (outStream != null) outStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataFile != null) dataFile.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e1) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "REST") {

            statusMessage.append("502 Sorry, no resuming");

          } else if (command == "TYPE") {

            if (Character.toUpperCase(str.charAt(0)) == 'I') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504 Only binary baybee");
            }

          } else if (command == "DELE"
              || command == "RMD"
              || command == "XRMD"
              || command == "MKD"
              || command == "XMKD"
              || command == "RNFR"
              || command == "RNTO"
              || command == "CDUP"
              || command == "XCDUP"
              || command == "CWD"
              || command == "SIZE"
              || command == "MDTM") {

            statusMessage.append("502 None of that malarky!");

          } else if (command == "QUIT") {

            statusMessage.append(COMMAND_OK).append("GOOD BYE");
            done = true;

          } else if (command == "PWD" | command == "XPWD") {

            statusMessage.append("257 \"/\" is current directory");

          } else if (command == "PORT") {

            int lng, lng1, lng2, ip2;
            String a1 = "", a2 = "";
            lng = str.length() - 1;
            lng2 = str.lastIndexOf(",");
            lng1 = str.lastIndexOf(",", lng2 - 1);

            for (i = lng1 + 1; i < lng2; i++) {
              a1 = a1 + str.charAt(i);
            }

            for (i = lng2 + 1; i <= lng; i++) {
              a2 = a2 + str.charAt(i);
            }

            remotePort = Integer.parseInt(a1);
            ip2 = Integer.parseInt(a2);
            remotePort = (remotePort << 8) + ip2;
            statusMessage.append(COMMAND_OK).append(remotePort);

          } else if (command == "LIST" | command == "NLST") {

            try {

              out.println("150 ASCII data");
              dataSocket = setupDataLink();

              PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true);

              if ((command == "NLST")) {
                out2.println(".");
                out2.println("..");
              } else {
                out2.println("total 8.0k");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 .");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 ..");
              }

              // socket MUST be closed before signalling EOD
              dataSocket.close();
              dataSocket = null;
              statusMessage.setLength(0);
              statusMessage.append(XFER_COMPLETE);
            } finally {
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "NOOP") {

            statusMessage.append(COMMAND_OK);

          } else if (command == "SYST") {

            statusMessage.append("215 UNIX"); // allows NS to do long dir

          } else if (command == "MODE") {

            if (Character.toUpperCase(str.charAt(0)) == 'S') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "STRU") {

            if (str.equals("F")) {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "PASV") {

            try {

              int num = 0, j = 0;
              if (passiveSocket != null)
                try {
                  passiveSocket.close();
                } catch (Exception e) {
                }
              ;
              passiveSocket = new ServerSocket(0); // any port

              // ensure timeout on reads.
              passiveSocket.setSoTimeout(inactivityTimer);

              statusMessage.append("227 Entering Passive Mode (");
              String s = localNode.getHostAddress().replace('.', ','); // get host #
              statusMessage.append(s).append(',');
              num = passiveSocket.getLocalPort(); // get port #
              j = (num >> 8) & 0xff;
              statusMessage.append(j);
              statusMessage.append(',');
              j = num & 0xff;
              statusMessage.append(j);
              statusMessage.append(')');
            } catch (Exception e) {
              try {
                if (passiveSocket != null) passiveSocket.close();
              } catch (Exception e1) {
              }
              ;
              passiveSocket = null;
              throw e;
            }

          } else {
            statusMessage.append("502 unimplemented ").append(command);
          }
        }

        // shutdown causes an interruption to be thrown
        catch (InterruptedException e) {
          throw (e);
        } catch (Exception e) // catch all for any errors (including files)
        {
          statusMessage.append(FAULT).append(e.getMessage());
          if (debug) {
            System.out.println("\nFAULT - lastfile " + targetFile);
            e.printStackTrace();
          }
          ;
        }

        // send result status to remote
        out.println(statusMessage);
        if (log) System.out.println("\t" + statusMessage);
      }
    } catch (Exception e) // usually network errors (including timeout)
    {
      if (log) System.out.println("forced instance exit " + e);
      if (debug) e.printStackTrace();
    } finally // exiting server instance
    {
      // tear down mysql
      if (this.db_rs != null) {
        try {
          this.db_rs.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_stmt != null) {
        try {
          this.db_stmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_pstmt != null) {
        try {
          this.db_pstmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_conn != null) {
        try {
          this.db_conn.close();
        } catch (SQLException SQLE) {;
        }
      }

      forceClose();
    }
  }
  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @param pageNo 页号
   * @param rowsPerPage 每页的行数
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions, int pageNo, int rowsPerPage)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("UserNo,");
    buffer.append("UserName,");
    buffer.append("Address,");
    buffer.append("ReadDate,");
    buffer.append("StatMonth,");
    buffer.append("ThisWorkNum,");
    buffer.append("MidWorkNum,");
    buffer.append("LastWorkNum,");
    buffer.append("Rate,");
    buffer.append("ReadQuantity,");
    buffer.append("ExcepQuantity,");
    buffer.append("ChgAmmeterQuantity,");
    buffer.append("CompensateQuantity,");
    buffer.append("AppendCalQuantity,");
    buffer.append("TranferLossQuantity,");
    buffer.append("PeoplePrice,");
    buffer.append("NotPeoplePrice,");
    buffer.append("FarmPrice,");
    buffer.append("ProducePrice,");
    buffer.append("BusinessPrice,");
    buffer.append("Voltlevel,");
    buffer.append("IndustryPrice,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("InputDate ");
    buffer.append("FROM LwTownIndicator WHERE ");
    buffer.append(conditions);
    boolean supportPaging = false; // 数据库是否支持分页
    if (pageNo > 0) {
      // 对Oracle优化
      if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("Oracle")) {
        buffer.insert(0, "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (");
        buffer.append(
            ") row_ WHERE rownum <= "
                + rowsPerPage * pageNo
                + ") WHERE rownum_ > "
                + rowsPerPage * (pageNo - 1));
        supportPaging = true;
      } else if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("DB2")) {
        String sql = buffer.toString();
        buffer.setLength(0);
        buffer.append("select * from ( select rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) {
          buffer.append(sql.substring(orderByIndex));
        }
        buffer.append(") as rownumber_,");
        buffer.append(sql.substring(6));
        buffer.append(" ) as temp_ where rownumber_");
        buffer.append(
            " between " + (rowsPerPage * (pageNo - 1) + 1) + " and " + rowsPerPage * pageNo);
        supportPaging = true;
      }
    }
    if (true) {
      logger.debug(buffer.toString());
    }
    ResultSet resultSet = dbManager.executeQuery(buffer.toString());
    int count = 0;
    if (supportPaging == false && pageNo > 1) {
      dbManager.locate(resultSet, rowsPerPage * (pageNo - 1));
    }

    // 定义返回结果集合
    Collection collection = new ArrayList(rowsPerPage);
    LwTownIndicatorDto lwTownIndicatorDto = null;
    while (resultSet.next()) {
      if (supportPaging == false && pageNo > 0) {
        count++;
        if (count > rowsPerPage) {
          break;
        }
      }

      lwTownIndicatorDto = new LwTownIndicatorDto();
      lwTownIndicatorDto.setUserNo(dbManager.getString(resultSet, "UserNo"));
      lwTownIndicatorDto.setUserName(dbManager.getString(resultSet, "UserName"));
      lwTownIndicatorDto.setAddress(dbManager.getString(resultSet, "Address"));
      lwTownIndicatorDto.setReadDate(dbManager.getString(resultSet, "ReadDate"));
      lwTownIndicatorDto.setStatMonth(dbManager.getString(resultSet, "StatMonth"));
      lwTownIndicatorDto.setThisWorkNum(dbManager.getDouble(resultSet, "ThisWorkNum"));
      lwTownIndicatorDto.setMidWorkNum(dbManager.getDouble(resultSet, "MidWorkNum"));
      lwTownIndicatorDto.setLastWorkNum(dbManager.getDouble(resultSet, "LastWorkNum"));
      lwTownIndicatorDto.setRate(dbManager.getDouble(resultSet, "Rate"));
      lwTownIndicatorDto.setReadQuantity(dbManager.getDouble(resultSet, "ReadQuantity"));
      lwTownIndicatorDto.setExcepQuantity(dbManager.getDouble(resultSet, "ExcepQuantity"));
      lwTownIndicatorDto.setChgAmmeterQuantity(
          dbManager.getDouble(resultSet, "ChgAmmeterQuantity"));
      lwTownIndicatorDto.setCompensateQuantity(
          dbManager.getDouble(resultSet, "CompensateQuantity"));
      lwTownIndicatorDto.setAppendCalQuantity(dbManager.getLong(resultSet, "AppendCalQuantity"));
      lwTownIndicatorDto.setTranferLossQuantity(
          dbManager.getLong(resultSet, "TranferLossQuantity"));
      lwTownIndicatorDto.setPeoplePrice(dbManager.getDouble(resultSet, "PeoplePrice"));
      lwTownIndicatorDto.setNotPeoplePrice(dbManager.getDouble(resultSet, "NotPeoplePrice"));
      lwTownIndicatorDto.setFarmPrice(dbManager.getDouble(resultSet, "FarmPrice"));
      lwTownIndicatorDto.setProducePrice(dbManager.getDouble(resultSet, "ProducePrice"));
      lwTownIndicatorDto.setBusinessPrice(dbManager.getDouble(resultSet, "BusinessPrice"));
      lwTownIndicatorDto.setVoltlevel(dbManager.getInt(resultSet, "Voltlevel"));
      lwTownIndicatorDto.setIndustryPrice(dbManager.getDouble(resultSet, "IndustryPrice"));
      lwTownIndicatorDto.setValidStatus(dbManager.getString(resultSet, "ValidStatus"));
      lwTownIndicatorDto.setFlag(dbManager.getString(resultSet, "Flag"));
      lwTownIndicatorDto.setRemark(dbManager.getString(resultSet, "Remark"));
      lwTownIndicatorDto.setInputDate(dbManager.getString(resultSet, "InputDate"));
      collection.add(lwTownIndicatorDto);
    }
    resultSet.close();
    return collection;
  }
  /**
   * Print a dump of the current input or output network packet.
   *
   * @param streamId the owner of this packet
   * @param in true if this is an input packet
   * @param pkt the packet data
   */
  public static void logPacket(int streamId, boolean in, byte[] pkt) {
    int len = ((pkt[2] & 0xFF) << 8) | (pkt[3] & 0xFF);

    StringBuffer line = new StringBuffer(80);

    line.append("----- Stream #");
    line.append(streamId);
    line.append(in ? " read" : " send");
    line.append((pkt[1] != 0) ? " last " : " ");

    switch (pkt[0]) {
      case 1:
        line.append("Request packet ");
        break;
      case 2:
        line.append("Login packet ");
        break;
      case 3:
        line.append("RPC packet ");
        break;
      case 4:
        line.append("Reply packet ");
        break;
      case 6:
        line.append("Cancel packet ");
        break;
      case 14:
        line.append("XA control packet ");
        break;
      case 15:
        line.append("TDS5 Request packet ");
        break;
      case 16:
        line.append("MS Login packet ");
        break;
      case 17:
        line.append("NTLM Authentication packet ");
        break;
      case 18:
        line.append("MS Prelogin packet ");
        break;
      default:
        line.append("Invalid packet ");
        break;
    }

    println(line.toString());
    println("");
    line.setLength(0);

    for (int i = 0; i < len; i += 16) {
      if (i < 1000) {
        line.append(' ');
      }

      if (i < 100) {
        line.append(' ');
      }

      if (i < 10) {
        line.append(' ');
      }

      line.append(i);
      line.append(':').append(' ');

      int j = 0;

      for (; j < 16 && i + j < len; j++) {
        int val = pkt[i + j] & 0xFF;

        line.append(hex[val >> 4]);
        line.append(hex[val & 0x0F]);
        line.append(' ');
      }

      for (; j < 16; j++) {
        line.append("   ");
      }

      line.append('|');

      for (j = 0; j < 16 && i + j < len; j++) {
        int val = pkt[i + j] & 0xFF;

        if (val > 31 && val < 127) {
          line.append((char) val);
        } else {
          line.append(' ');
        }
      }

      line.append('|');
      println(line.toString());
      line.setLength(0);
    }

    println("");
  }