數據非空轉換類

 

package com.guanri.util;

import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import javax.servlet.http.HttpServlet;
import java.util.*;
import java.text.*;
import java.io.*;
import com.guanri.database.TableField;
import javax.servlet.http.*;
import com.boble.infrastructure.bous.*;

//import  com.guanri.util.RandomStringUtils;

public class Util {

//  private static Logger log = Logger.getInstance();
  private static String escapeStr = "@";

  public Util() {
  }

  /**
   * getRequestStr
   * @param request
   * @param name
   * @param defaultVal
   * @return
   */
  public static String getRequestStr(HttpServletRequest request, String name,
                                     String defaultVal) {
    return getRequestStr(request, name, defaultVal, false, true);
  }

  public static String getRequestStr(HttpServletRequest request, String name,
                                     String defaultVal, boolean needTrim) {
    return getRequestStr(request, name, defaultVal, needTrim, true);
  }

  public static String getRequestStr(HttpServletRequest request, String name,
                                     String defaultVal, boolean needTrim,
                                     boolean needConvert) {

    String val = defaultVal;
    try {
//      val = new String(request.getParameter(name).getBytes("ISO8859-1"),"GBK");
      val = request.getParameter(name);
      if (val == null) {
        val = defaultVal;
      }
    }
    catch (Exception e) {
//      log.log(e);
    }

    if (needTrim) {
      val = val.trim();

    }
    if (needConvert) {
      return Convert(val);
    }
    else {
      return val;
    }
  }

  public static int getRequestInt(HttpServletRequest request, String name,
                                  int defaultVal) {

    int val = defaultVal;
    try {
      val = new Integer(request.getParameter(name)).intValue();
    }
    catch (Exception e) {
//      log.log(e);
    }
    return val;
  }

  public static double getRequestDouble(HttpServletRequest request, String name,
                                        double defaultVal) {

    double val = defaultVal;
    try {
      val = new Double(request.getParameter(name)).doubleValue();
    }
    catch (Exception e) {
//      log.log(e);
    }
    return val;
  }

  public static BigDecimal getRequestNum(HttpServletRequest request,
                                         String name, BigDecimal defaultVal) {

    BigDecimal val = defaultVal;
    try {
      val = new BigDecimal(request.getParameter(name));
    }
    catch (Exception e) {
//      log.log(e);
    }
    return val;
  }

  /**
   * replace string
   * @param origin
   * @param src
   * @param dst
   * @return
   */
  public static String replace(String origin,
                               String src,
                               String dst) {
    if (src == null) {
      return dst;
    }
    if (dst == null) {
      return null;
    }

    StringBuffer sb = new StringBuffer();
    int len = src.length();
    int start = 0;
    int find = 0;
    while ( (find = origin.indexOf(src, start)) > -1) {
      sb.append(origin.substring(start, find));
      sb.append(dst);
      start = find + len;
    }
    sb.append(origin.substring(start));
    return sb.toString();
  }

  /**
   *
   * @param s
   * @return
   */
  public static String Convert(String s) {
    if (s == null) {
      return "";
    }

    String retStr = s;

//     retStr = s.trim();
    retStr = replace(retStr, "\"", "”");
    retStr = replace(retStr, "'", "’");
    retStr = replace(retStr, "<", "〈");
    retStr = replace(retStr, ">", "〉");
//     retStr = replace(retStr, "&", "&");
//      retStr = replace(retStr, "\n", "<br>");
//     retStr = replace(retStr, "\t", "&nbsp;&nbsp;&nbsp;");
    return retStr;
  }

  public static String Convert2HTML(String s) {
    String retStr = null;
    if (s == null) {
      return "";
    }
    retStr = s;
    retStr = replace(retStr, "\"", "“");
    retStr = replace(retStr, "'", "’");
    retStr = replace(retStr, "<", "&lt;");
    retStr = replace(retStr, ">", "&gt;");
    retStr = replace(retStr, "&", "&amp;");
    retStr = replace(retStr, " ", "&nbsp;");
    retStr = replace(retStr, "\n", "<br>");
    retStr = replace(retStr, "\t", "&nbsp;&nbsp;&nbsp;");
    return retStr;
  }

  public static String formatDate2Str(Date dt, String pattern) {
    String result = "";
    if (dt == null) {
      return result;
    }
    if (pattern == null) {
      pattern = "yyyy-MM-dd";
    }
    try {
      SimpleDateFormat format = new SimpleDateFormat(pattern);
      result = format.format(dt);
    }
    catch (Exception e) {}
    return result;
  }

  public static String getCurrentDateStr() {
    return formatDate2Str(new Date(System.currentTimeMillis()), "yyyy-MM-dd");
  }

  /**
   *Add by xzh 2003-11-06
   * begin
   */
  public static String getCurrentDateStr(String sType) {
    return formatLongValue2DateStr(System.currentTimeMillis(), sType);
  }

  //end
  public static Date formatStr2Date(String dt, String pattern) {
    Date result = null;
    try {
      SimpleDateFormat format = new SimpleDateFormat(pattern);
      result = format.parse(dt);
    }
    catch (Exception e) {}
    return result;
  }

  public static String formatLong2DateStr(Long number, String pattern) {
    String str = null;
    try {
      Date date = new Date(number.longValue());
      str = formatDate2Str(date, pattern);
    }
    catch (Exception e) {}
    return str;
  }

  public static String formatLongValue2DateStr(long number, String pattern) {
    String str = null;
    if (number <= 0) {
      return "";
    }
    try {
      Date date = new Date(number);
      str = formatDate2Str(date, pattern);
    }
    catch (Exception e) {}
    return str;
  }

  public static Long formatDateStr2Long(String dt, String pattern) {
    Long result = null;
    try {
      Date date = formatStr2Date(dt, pattern);
      result = new Long(date.getTime());
    }
    catch (Exception e) {}
    return result;
  }

  public static long formatDateStr2LongValue(String dt, String pattern) {
    long result = 0;
    try {
      Date date = formatStr2Date(dt, pattern);
      result = date.getTime();
    }
    catch (Exception e) {}
    return result;
  }

  public static String createRandomId() {
    String sTempId = String.valueOf(new java.util.Date().getTime());
    sTempId += RandomStringUtils.random(10, true, true);
    return sTempId;
  }

  public static String createRandomId(int count, boolean letters,
                                      boolean numbers) {
    return RandomStringUtils.random(count, letters, numbers);
  }

  public static String formatNumber(int n, String pattern) {
    String result = "";
    try {
      DecimalFormat df = new DecimalFormat(pattern);
      result = df.format(n);
    }
    catch (Exception e) {}
    return result;
  }

  public static String formatNumber(double n, String pattern) {
    String result = "";
    try {
      DecimalFormat df = new DecimalFormat(pattern);
      result = df.format(n);
    }
    catch (Exception e) {}
    return result;
  }

  public static String formatNumber(long n, String pattern) {
    String result = "";
    try {
      DecimalFormat df = new DecimalFormat(pattern);
      result = df.format(n);
    }
    catch (Exception e) {}
    return result;
  }

  public static int cauRows(Vector v, String sField, String delv_no) {
    int count = 0;
    Hashtable hs = null;
    for (int i = 0; i < v.size(); i++) {
      hs = (Hashtable) v.get(i);
      if (delv_no.equals(hs.get(sField).toString().trim())) {
        count++;
      }
    }
    return count;
  }

  /**
   * 文件拷貝(單個)
   */
  public static boolean copy(String from, String to) {
    try {
      to = replace(to, "\\", "/");
      String toPath = to.substring(0, to.lastIndexOf("/"));
      File f = new File(toPath);
      if (!f.exists()) {
        f.mkdirs();
      }
      BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
          from));
      BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(
          to));
      int c;
      while ( (c = bin.read()) != -1) {
        bout.write(c);
      }
      bin.close();
      bout.close();
      return true;
    }
    catch (Exception e) {
      return false;
    }
  }

  /**
   * 目錄拷貝
   */
  public static boolean xcopy(String from, String to) {
    from = replace(from, "\\", "/");
    to = replace(to, "\\", "/");
    if (!from.endsWith("/")) {
      from = from + "/";
    }
    if (!to.endsWith("/")) {
      to = to + "/";
    }
    File tt = new File(to);
    if (!tt.exists()) {
      tt.mkdirs();
    }
    String ss = "";
    File ff = new File(from);
    if (ff.isDirectory()) {
      File f[] = ff.listFiles();
      for (int i = 0; i < f.length; i++) {
        String temp = f[i].getName();
        if (f[i].isDirectory()) {

          File g = new File(to + temp);
          if (!g.exists()) {
            g.mkdirs();
          }
        }
        else {
          copy(from + temp, to + temp);
        }
        xcopy(from + temp, to + temp);
      }
    }
    return true;
  }

  public static boolean checkPurview(String sPurview, int postion,
                                     String checkValue) {
    if (sPurview == null || sPurview.trim().equals("")) {
      return false;
    }
    String sTemp = sPurview.substring(postion, postion + 1);
    //System.out.println(sTemp);
    if (sTemp.equals(checkValue)) {
      return true;
    }
    else {
      return false;
    }
  }

  /**
   *得到兩個日期相差的天數
   *
   * @param stime  開始時間
   * @param etime  結束時間
   * @return
   */
  public static long getDateDiff(Date stime, Date etime) {
    if (stime == null || etime == null) {
      return 0;
    }

    //相差毫秒數
    long i = etime.getTime() - stime.getTime();
    //整除
    long j = i / (24 * 60 * 60 * 1000);
    //求餘
    long k = i % (24 * 60 * 60 * 1000);
    //如果相差不爲0,同時餘數大於0,則加一天
    if (i != 0 && k != 0) {
      j++;
    }
    return j;
  }

  /**
   *通過發英文代碼獲取中文發運字串
   * @param delv_method  發運英文代碼
   * @param etime  結束時間
   * @return
   */
  public static String getDelvMethod(String delv_method) {
    TableField[] arrTf = new TableField[6];
    arrTf[0] = new TableField("包裹", "PACK");
    arrTf[1] = new TableField("汽運", "CAR");
    arrTf[2] = new TableField("中鐵", "TRAN");
    arrTf[3] = new TableField("特快專遞", "EMS");
    arrTf[4] = new TableField("航空", "AIR");
    arrTf[5] = new TableField("大巴", "BUS");
    for (int i = 0; i < arrTf.length; i++) {
      if (delv_method.equalsIgnoreCase(arrTf[i].getValue().toString())) {
        return arrTf[i].getName();
      }
    }
    return "";
  }

  public static String convertByte2HexString(byte[] bytes) {
    char[] hex = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
        'E', 'F'};

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
      sb.append(hex[ (int) (bytes[i] & 0x0F)]);
      sb.append(hex[ (int) (bytes[i] >> 4 & 0x0F)]);
    }

    return sb.toString();
  }

  /**
   * 模糊查詢的字符串的轉換
   * @param sStr
   * @return
   */
  public static String Str2Like(String sStr) {
    String sResult = sStr;
    if (sStr != null && !sStr.trim().equals("")) {
      sResult = "%" + sStr + "%";
    }
    return sResult;
  }

  public static String getCostNo(HttpServletRequest request, String sType) {
    try {
      HttpSession session = request.getSession();
      String sDEMPNO = ( (String) session.getAttribute("EMPNO")).trim();
      String sResult = sDEMPNO.substring(sDEMPNO.length() - 3) +
          sType.toUpperCase() + getCurrentDateStr("yyMMdd");
      //System.out.println("in util for test the getCurrentDateStr getCurrentDateStr(\"yMMddHHmm\"):"+getCurrentDateStr("yMMddHHmm")+" getCurrentDateStr(\"MMddHHmm\"):"+getCurrentDateStr("MMddHHmm")+" getCurrentDateStr(\"MMddHHmm\"):"+getCurrentDateStr("MMddHHmm"));
      return sResult;
    }
    catch (Exception ex) {
      return null;
    }

  }

  /**
   * 處理sql中like語句的特殊字符
   */
  public static String EscapeLikeWhere(String sWhere) {
    if (sWhere == null || sWhere.trim().equals("")) {
      return sWhere;
    }
    sWhere = EscapeWhere(sWhere);
    //sWhere = sWhere.replaceAll("\"", escapeStr + "\"");
    sWhere = sWhere.replaceAll("%", escapeStr + "%");
    return sWhere;
  }

  /**
   * 處理sql的where條件的特殊字符
   */

  public static String EscapeWhere(String sWhere) {
    if (sWhere == null || sWhere.trim().equals("")) {
      return sWhere;
    }
    sWhere = sWhere.replaceAll("'", "''");
    return sWhere;
  }

  /**
   * 數據庫的條件語句的加入
   * @param sField 字段名
   * @param sValue 字段值
   * @param sType 比較類型
   * @param sLinkType 連接形式
   * @return
   */
  public static StringBuffer AddWhere(StringBuffer sWhere, String sField,
                                      String sValue,
                                      String sType, String sLinkType,
                                      String sFieldType) {

    if (sLinkType == null) {
      sLinkType = "and";
    }
    if (sWhere == null || sWhere.toString().trim().equals("")) {
      sLinkType = "";
    }
    //like連接類型
    if (sType != null && sField != null && sValue != null &&
        !sField.trim().equals("")) {
      if (sType.trim().toLowerCase().equals("like")) {
        sWhere.append(EscapeLikeSql(" " + sLinkType + " (" + sField +
                                    " like '%" +
                                    EscapeLikeWhere(sValue) + "%'") + ")");

      }
      else {
        if (sFieldType != null && sFieldType.trim().equals("")) {
          sWhere.append(" " + sLinkType + " (" + sField
                        + sType + "'" +
                        sValue + "')");
        }
        else if (sFieldType != null &&
                 sFieldType.trim().toLowerCase().equals("date")) {
          sWhere.append(" " + sLinkType + " (" + sField
                        + sType + "" + formatDateStr2LongValue(sValue,
              VariableNames.YYYYMMDD) +
                        ")");

        }

      }

    } //其餘連接類型
    else {
      System.out.println("sType or sField  or sValue is null(space)");
    }
    return sWhere;
  }

  /**
   *
   * @param sWhere
   * @param sField
   * @param sValue
   * @param sType
   * @param sLinkType
   * @return
   */
  public static StringBuffer AddWhere(StringBuffer sWhere, String sField,
                                      String sValue,
                                      String sType, String sLinkType) {
    return AddWhere(sWhere, sField, sValue, sType, sLinkType, "");
  }

  /**
   * 處理sql的特殊字符,escape
   * @param sSql
   * @return
   */
  public static String EscapeLikeSql(String sSql) {
    if (sSql != null && !sSql.trim().equals("")) {
      return (sSql + " {escape '" + escapeStr + "'}");
    }
    else {
      return sSql;
    }
  }

  public static String Long2Date(long lLong) {
    return formatLongValue2DateStr(lLong, VariableNames.YYYYMMDD);
  }

  public static String Long2Date(Long lLong) {
    try {
      return Long2Date(lLong.longValue());
    }
    catch (Exception ex) {
      return "";
    }
  }

  /**
   * 把Null轉換爲空字符串
   */
  public static String Null2Space(String sStr) {
    if (sStr == null) {
      sStr = "";
    }
    return sStr;
  }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章