自动化测试框架

package main;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import impl.RESTClientImpl;
import util.ExcelData;
import util.ModifyExcel;
import util.RegularUtils;
import rest.RESTClientUtils;

public class LogicCheckOneWayRestAPI
{
  private Logger logger = Logger.getLogger(LogicCheckOneWayRestAPI.class);
  public static String tokenID = "";
  private boolean loginResult = false;

  public boolean oneWayRestTest(String restAPIPath, String jsonInfo, String responseInfo, String resultFlag)
  {
    HashMap resMap = new HashMap();
    boolean resFlage = false;

    String temp_jsonInfo = "";
    try
    {
      RESTClientImpl restClient = new RESTClientImpl();
      RESTClientUtils restUtils = new RESTClientUtils();

      temp_jsonInfo = setTokenInfo(jsonInfo, restUtils);

      HttpResponse result = restClient.post(restAPIPath, temp_jsonInfo);
      if (result.toString().contains("200 OK"))
      {
        String str_result = EntityUtils.toString(result.getEntity(), 
          "UTF-8");

        if ((str_result != null) && (!"".equals(str_result))) {
          resMap = RESTClientUtils.parseJSONtoMAP(str_result);
          String s_value = (String)resMap.get("success");
          String d_value = (String)resMap.get("data");
          String p_value = (String)resMap.get("params");
          String t_value = null;
          if (d_value.contains("total"))
            t_value = (String)RESTClientUtils.parseJSONtoMAP(d_value).get("total");
          if (restAPIPath.contains("system/login")) {
            tokenID = StringUtils.substringBetween(p_value, "[\"", 
              "\"]");
          }

          if (resultFlag.equalsIgnoreCase(s_value)) {
            this.logger.info("rest API " + restAPIPath + 
              " ");
            if ((("true".equalsIgnoreCase(s_value)) && (d_value.contains(responseInfo))) || (t_value.equals("0")))
            {
              resFlage = true;
              this.logger.info("rest API " + restAPIPath + 
                " "+ str_result);
            } else {
              this.logger.info("rest API " + restAPIPath + 
                " " + str_result);
            }
          } else {
            this.logger.info("rest API " + restAPIPath + 
              " "+ str_result);
          }
        } else {
          this.logger.info("rest API " + restAPIPath + " " + 
            str_result);
        }
      }
    } catch (Throwable e) {
      this.logger.info("rest API " + restAPIPath + " 婵炴潙顑堥惁顖炲礄濞差亝鏅�" + 
        e.getMessage());
      e.printStackTrace();
    }
    return resFlage;
  }

  public String setTokenInfo(String jsonInfo, RESTClientUtils restUtils)
  {
    HashMap temp_jsonMap = RESTClientUtils.parseJSONtoMAP(jsonInfo);
    temp_jsonMap.put("token", tokenID);
    String temp_jsonInfo = JSONObject.fromObject(temp_jsonMap).toString();
    return temp_jsonInfo;
  }

  public void loopExc(String filePath)
  {
    boolean result = false;
    int CaseNum = 1;
    int passNum = 0;
    Map s = new TreeMap();
    ExcelData iter = new ExcelData(filePath);
    String startTime = "StartTime闁挎冻鎷� "+ getCurrentTime();
    long startT = System.currentTimeMillis();
    this.logger.info("=========Test cases of " + RegularUtils.getTestcaseFileName(filePath) + " begin=========\n");
    ModifyExcel me = new ModifyExcel(filePath, filePath);
    me.setSheet(1);
    while (iter.hasNext())
    {
      Object[] str = iter.next();
      s = (Map)str[0];
      String url = null;
      String jsonInfo = null;
      String expectInfo = null;
      String resultFlag = null;
      try {
        url = ((String)s.get("url")).toString().trim();
        if (url.equalsIgnoreCase("finish"))
          break;
        jsonInfo = URLDecoder.decode(((String)s.get("jsonInfo")).toString().trim(), "UTF-8");
        expectInfo = URLDecoder.decode(((String)s.get("expectInfo")).toString().trim(), "UTF-8");
        resultFlag = ((String)s.get("resultFlag")).toString().trim();
      } catch (UnsupportedEncodingException e) {
        this.logger.info("UnsupportedEncodingException");
        e.printStackTrace();
      }

      if (url.contains("system/login")) {
        this.loginResult = oneWayRestTest(url, jsonInfo, expectInfo, 
          resultFlag);
        result = this.loginResult;
      }
      else if (this.loginResult) {
        result = oneWayRestTest(url, jsonInfo, expectInfo, resultFlag);
      }
      else {
        this.logger.info("Login rest API failed, so did not run this rest api : " + url + "\n");
      }
      if (result) {
        passNum++;
        this.logger.info("Case " + CaseNum + " rest API passed : " + url + "\n");
      } else {
        me.modifycell(4, CaseNum, "failed");
        this.logger.info("Case " + CaseNum + " rest API failed : " + url + "\n");
      }
      CaseNum++;
    }
    this.logger.info("totle Case :" + CaseNum + " passed : " + passNum + "\n");
    String endTime = "EndTime闁挎冻鎷�" + getCurrentTime();
    long endT = System.currentTimeMillis();
    me.setSheet(0);
    me.modifycell(0, 1, startTime);
    me.modifycell(0, 2, endTime);
    me.modifycell(0, 3, getLastTime(endT - startT));
    me.modifycell(1, 5, String.valueOf(passNum));
    me.modifycell(1, 6, String.valueOf(CaseNum - passNum));
    me.modifycell(1, 8, String.valueOf(CaseNum));
    me.close();
    this.logger.info("=========Test end=========\n\n\n\n");
  }
  public String getCurrentTime() {
    Date date = new Date();
    SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String time = matter.format(date);
    return time;
  }
  public String getLastTime(long time) {
    String str = "LastTime:";
    long msec = time % 1000L;
    long sec = time / 1000L % 60L;
    long min = time / 1000L / 60L % 60L;
    long hr = time / 1000L / 60L / 60L % 24L;
    long d = time / 1000L / 60L / 60L / 24L % 30L;
    str = str + String.valueOf(d) + "d " + 
      String.valueOf(hr) + "hr " + 
      String.valueOf(min) + "min " + 
      String.valueOf(sec) + "sec " + 
      String.valueOf(msec) + "msec ";
    return str;
  }
}



package main;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import impl.RESTClientImpl;
import util.ExcelData;
import util.ModifyExcel;
import util.RegularUtils;
import rest.RESTClientUtils;

public class LogicCheckOneWayRestAPI
{
  private Logger logger = Logger.getLogger(LogicCheckOneWayRestAPI.class);
  public static String tokenID = "";
  private boolean loginResult = false;

  public boolean oneWayRestTest(String restAPIPath, String jsonInfo, String responseInfo, String resultFlag)
  {
    HashMap resMap = new HashMap();
    boolean resFlage = false;

    String temp_jsonInfo = "";
    try
    {
      RESTClientImpl restClient = new RESTClientImpl();
      RESTClientUtils restUtils = new RESTClientUtils();

      temp_jsonInfo = setTokenInfo(jsonInfo, restUtils);

      HttpResponse result = restClient.post(restAPIPath, temp_jsonInfo);
      if (result.toString().contains("200 OK"))
      {
        String str_result = EntityUtils.toString(result.getEntity(), 
          "UTF-8");

        if ((str_result != null) && (!"".equals(str_result))) {
          resMap = RESTClientUtils.parseJSONtoMAP(str_result);
          String s_value = (String)resMap.get("success");
          String d_value = (String)resMap.get("data");
          String p_value = (String)resMap.get("params");
          String t_value = null;
          if (d_value.contains("total"))
            t_value = (String)RESTClientUtils.parseJSONtoMAP(d_value).get("total");
          if (restAPIPath.contains("system/login")) {
            tokenID = StringUtils.substringBetween(p_value, "[\"", 
              "\"]");
          }

          if (resultFlag.equalsIgnoreCase(s_value)) {
            this.logger.info("rest API " + restAPIPath + 
              " ");
            if ((("true".equalsIgnoreCase(s_value)) && (d_value.contains(responseInfo))) || (t_value.equals("0")))
            {
              resFlage = true;
              this.logger.info("rest API " + restAPIPath + 
                " "+ str_result);
            } else {
              this.logger.info("rest API " + restAPIPath + 
                " " + str_result);
            }
          } else {
            this.logger.info("rest API " + restAPIPath + 
              " "+ str_result);
          }
        } else {
          this.logger.info("rest API " + restAPIPath + " " + 
            str_result);
        }
      }
    } catch (Throwable e) {
      this.logger.info("rest API " + restAPIPath + " 婵炴潙顑堥惁顖炲礄濞差亝鏅�" + 
        e.getMessage());
      e.printStackTrace();
    }
    return resFlage;
  }

  public String setTokenInfo(String jsonInfo, RESTClientUtils restUtils)
  {
    HashMap temp_jsonMap = RESTClientUtils.parseJSONtoMAP(jsonInfo);
    temp_jsonMap.put("token", tokenID);
    String temp_jsonInfo = JSONObject.fromObject(temp_jsonMap).toString();
    return temp_jsonInfo;
  }

  public void loopExc(String filePath)
  {
    boolean result = false;
    int CaseNum = 1;
    int passNum = 0;
    Map s = new TreeMap();
    ExcelData iter = new ExcelData(filePath);
    String startTime = "StartTime闁挎冻鎷� "+ getCurrentTime();
    long startT = System.currentTimeMillis();
    this.logger.info("=========Test cases of " + RegularUtils.getTestcaseFileName(filePath) + " begin=========\n");
    ModifyExcel me = new ModifyExcel(filePath, filePath);
    me.setSheet(1);
    while (iter.hasNext())
    {
      Object[] str = iter.next();
      s = (Map)str[0];
      String url = null;
      String jsonInfo = null;
      String expectInfo = null;
      String resultFlag = null;
      try {
        url = ((String)s.get("url")).toString().trim();
        if (url.equalsIgnoreCase("finish"))
          break;
        jsonInfo = URLDecoder.decode(((String)s.get("jsonInfo")).toString().trim(), "UTF-8");
        expectInfo = URLDecoder.decode(((String)s.get("expectInfo")).toString().trim(), "UTF-8");
        resultFlag = ((String)s.get("resultFlag")).toString().trim();
      } catch (UnsupportedEncodingException e) {
        this.logger.info("UnsupportedEncodingException");
        e.printStackTrace();
      }

      if (url.contains("system/login")) {
        this.loginResult = oneWayRestTest(url, jsonInfo, expectInfo, 
          resultFlag);
        result = this.loginResult;
      }
      else if (this.loginResult) {
        result = oneWayRestTest(url, jsonInfo, expectInfo, resultFlag);
      }
      else {
        this.logger.info("Login rest API failed, so did not run this rest api : " + url + "\n");
      }
      if (result) {
        passNum++;
        this.logger.info("Case " + CaseNum + " rest API passed : " + url + "\n");
      } else {
        me.modifycell(4, CaseNum, "failed");
        this.logger.info("Case " + CaseNum + " rest API failed : " + url + "\n");
      }
      CaseNum++;
    }
    this.logger.info("totle Case :" + CaseNum + " passed : " + passNum + "\n");
    String endTime = "EndTime闁挎冻鎷�" + getCurrentTime();
    long endT = System.currentTimeMillis();
    me.setSheet(0);
    me.modifycell(0, 1, startTime);
    me.modifycell(0, 2, endTime);
    me.modifycell(0, 3, getLastTime(endT - startT));
    me.modifycell(1, 5, String.valueOf(passNum));
    me.modifycell(1, 6, String.valueOf(CaseNum - passNum));
    me.modifycell(1, 8, String.valueOf(CaseNum));
    me.close();
    this.logger.info("=========Test end=========\n\n\n\n");
  }
  public String getCurrentTime() {
    Date date = new Date();
    SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String time = matter.format(date);
    return time;
  }
  public String getLastTime(long time) {
    String str = "LastTime:";
    long msec = time % 1000L;
    long sec = time / 1000L % 60L;
    long min = time / 1000L / 60L % 60L;
    long hr = time / 1000L / 60L / 60L % 24L;
    long d = time / 1000L / 60L / 60L / 24L % 30L;
    str = str + String.valueOf(d) + "d " + 
      String.valueOf(hr) + "hr " + 
      String.valueOf(min) + "min " + 
      String.valueOf(sec) + "sec " + 
      String.valueOf(msec) + "msec ";
    return str;
  }
}

package common;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import rest.RESTClientUtils;

public class Dependent {
	private static Logger fLogger = Logger.getLogger(Dependent.class);
	protected HashMap<String,String> dependencyMap;
	protected HashMap<String,String> priID_DevIDMap = new HashMap();
	private String dataInfo;
	
	public HashMap<String, String> getDependencyMap() {
		return dependencyMap;
	}
	public void setDependencyMap(HashMap<String, String> dependencyValue) {
		this.dependencyMap = dependencyValue;
	}
	public HashMap<String, String> getPriID_DevIDMap() {
		return priID_DevIDMap;
	}
	public void setPriID_DevIDMap(HashMap<String, String> priID_DevIDMap) {
		this.priID_DevIDMap = priID_DevIDMap;
	}
	
	public Dependent(){
		this.dataInfo = "";
		this.dependencyMap = new HashMap();
	}
	
	public Dependent(String dataInfo){
		this.dataInfo = dataInfo;
		this.dependencyMap = new HashMap();
	}
	
	public String getDataInfo(){
		return this.dataInfo;
	}
	
	public void setDataInfo(String dataInfo){
		this.dataInfo = dataInfo;
	}
	
	public void updatekeys(String updatekeysInfo){
		HashMap updateKey = RESTClientUtils.parseJSONtoMAP(updatekeysInfo);
		Set<Entry<String,String>> set = updateKey.entrySet();
		for(Entry<String,String> entry :set){
			String oldKey = (String) entry.getKey();
			String newKey = (String) entry.getValue();
			String value = (String) this.dependencyMap.get(oldKey);
			this.dependencyMap.remove(oldKey);
			this.dependencyMap.put(newKey, value);
		}
	}
	
	public void clearDependency(){
		this.dependencyMap.clear();
	}
	
	public void setKey(String[] arr) {
		for (int i = 0; i < arr.length; i++) {
			if (this.dependencyMap.containsKey(arr[i])){
				return;	
			}
			this.dependencyMap.put(arr[i], "");
		}
	}
	
	public String setJsonDepencyInfo(String jsonInfo){
		if(!this.dependencyMap.isEmpty()){
			HashMap temp_jsonMap = RESTClientUtils.parseJSONtoMAP(jsonInfo);
			Set<Entry<String,String>>set = temp_jsonMap.entrySet();
			for (Map.Entry entry : set){
				temp_jsonMap.put((String)entry.getKey(),(String)entry.getValue());
			}
			jsonInfo = JSONObject.fromObject(temp_jsonMap).toString();
		}
		return jsonInfo;
	}
	
	
	public boolean addDependencyValue(String Info){
		Map singleInfo = null;
		if (Info.contains("\"list\":[")) {
		      Map map = RESTClientUtils.parseJSONtoMAP(Info);
		      String list = (String)map.get("list");
		      JSONArray listInfo = JSONArray.fromObject(
		        RESTClientUtils.parseJSONtoMAP(Info).get("list"));
		      if (listInfo.size() != 1) {
		        fLogger.info("The Query Result is not one row. " + 
		          listInfo.toString());
		      }
		      singleInfo = RESTClientUtils.parseJSONtoMAP(listInfo.get(0)
		        .toString());
		    }
		else{
			singleInfo = RESTClientUtils.parseJSONtoMAP(Info);
		}
		
		if(this.dependencyMap.isEmpty()){
			fLogger.info("The dependency map key is empty.");
			return false;
		}
		
		if(singleInfo == null){
			fLogger.info("The response Info contains no data or list.");
			return false;
		}
		
		Set<Entry<String,String>> valueMap = singleInfo.entrySet();//以键值对的形式取出
		HashMap<String,String> tmpvaluemap = new HashMap<String,String>();
		
		for(Entry<String,String> entry:valueMap){
			if(((String)entry.getValue()).contains("{")){
				tmpvaluemap = parsekeyvalueJson(tmpvaluemap,(String)entry.getValue());
			}
		}
		
		singleInfo.putAll(tmpvaluemap);
		Set<Entry<String,String>> set = dependencyMap.entrySet();
		for(Entry<String,String> entry:set){
			addDependency((String)entry.getKey(),(String)singleInfo.get(entry.getKey()));
		}
		
		fLogger.info("dependencyValue:" + this.dependencyMap.toString());
		return true;
	}
	
	
	public boolean addPerIDDevID_DependencyValue(){
		return false;
	}
	
	public HashMap<String,String> parsekeyvalueJson(HashMap<String,String>singleInfo,String value){
		Map map = RESTClientUtils.parseJSONtoMAP(value);
		singleInfo.putAll(map);
		return singleInfo;
	}
	
	public void addDependency(String key,String value){
		String tmpValue = (String) this.dependencyMap.get(key);
		if((tmpValue == null) || (tmpValue.isEmpty())){
			this.dependencyMap.put(key, value);
		}else{
			tmpValue = tmpValue + "," + value;
			this.dependencyMap.put(key, tmpValue);
		}
	}
	
	public String toString(){
		return this.dependencyMap.toString();
	}
}



package common;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import commonlogic.CommonLogicContainer;
import utils.db.ResultWrapper;
import util.ExcelData;
import util.ModifyExcel;
import utils.db.ResultWrapper;
import utils.db.SQLWrapper;

public class LogicRestCases
{
  private static Logger fLogger = Logger.getLogger(LogicRestCases.class);
  private static boolean loginResult = true;

  private StringBuffer logInfo = null; private ArrayList<TestCaseContain> Caseslist = new ArrayList();

  private String filePath = "";
  private String url = "";

  public List<TestCaseContain> getCaseslist()
  {
    return this.Caseslist;
  }
  public void setlogInfo(StringBuffer log) {
    this.logInfo = log; } 
  public void setFilePath(String path) { this.filePath = path; }

  public void putInCaseList(TestCaseContain value) {
    this.Caseslist.add(value);
  }

  public int runCases()
  {
    boolean result = false;
    int caseNum = 1;
    int passNum = 0;
    for (int i = 0; i < this.Caseslist.size(); i++)
    {
      TestCaseContain testcase = (TestCaseContain)this.Caseslist.get(i);
      if (testcase.getUrl().contains("system/login"))
      {
        loginResult = testcase.runCase();
        if (loginResult)
        {
          String log = "Case " + caseNum + " rest API passed : " + testcase.getUrl();
          this.logInfo.append(log);
          this.logInfo.append("\n");
          passNum++;
          fLogger.info("Case " + caseNum + " rest API passed : " + testcase.getUrl());
        }
        else
        {
          String log = "Case " + caseNum + " rest API failed : " + testcase.getUrl();
          this.logInfo.append(log);
          this.logInfo.append("\n");
          ModifyExcel.modifyCell(this.filePath, 1, 10, caseNum, "failed");
          fLogger.info("Case " + caseNum + " rest API failed : " + testcase.getUrl());
        }
      }
      else if (loginResult)
      {
        if (testcase.getDependentInfo().isEmpty())
        {
             result = testcase.runCase();
        
        }
        else
        {
          if (!runDepency(testcase))
          {
            String log = "Case " + caseNum + " rest API failed : " + testcase.getUrl() + " because the dependency case failed.";
            this.logInfo.append(log);
            this.logInfo.append("\n");
            fLogger.info(log);
          }
          result = testcase.runCase();
        }
        if (result)
        {
          String log = "Case " + caseNum + " rest API passed : " + testcase.getUrl();
          this.logInfo.append(log);
          this.logInfo.append("\n");
          fLogger.info(log);
          passNum++;
        }
        else
        {
          String log = "Case " + caseNum + " rest API failed : " + testcase.getUrl();
          this.logInfo.append(log);
          this.logInfo.append("\n");
          fLogger.info(log);
          ModifyExcel.modifyCell(this.filePath, 1, 10, caseNum, "failed");
        }
      }
      else
      {
        String log = "Case " + caseNum + " Login rest API failed, so did not run this rest api : " + testcase.getUrl();
        this.logInfo.append(log);
        this.logInfo.append("\n");
        fLogger.info(log);
      }
      caseNum++;
    }
    return passNum;
  }

  private boolean runDepency(TestCaseContain testcase)
  {
    testcase.getUrl().contains("workflow/rejectOpreateTicket");

    if ((testcase.getDependentInfo() != null) && (testcase.getDependentInfo().contains("database"))) {
      String testDependence = testcase.getDependentInfo();
      String[] arrStr = testDependence.split("@");
      ArrayList sqlResult = new ArrayList();
      for (String s : arrStr) {
        JSONObject jsonobj = JSONObject.fromObject(s);
        String dependency = jsonobj.getString("dependency");
        String valuetype = null;
        if (jsonobj.containsKey("valuetype")) {
          valuetype = jsonobj.getString("valuetype");
        }
        String action = "select ";
        String[] dep = dependency.split("&");
        String sql = jsonobj.containsKey("sql") ? jsonobj.getString("sql") : getExecSql(jsonobj, action, sqlResult);

        if (testcase.getUrl().contains("workflow/rejectOpreateTicket")) {
          System.out.println(sql);
        }

        try
        {
          new SQLWrapper(); ResultWrapper raw = SQLWrapper.getResult("MYSQL", "epmsgroup", this.url, "3308", "system", "Hwsystem@com", sql);
          if (raw.getListResult().size() < 1) {
            return false;
          }
          ArrayList str = new ArrayList();
          for (int j = 1; j < raw.getRowCount() + 1; j++) {
            if (raw.getString(j, 1) != null) {
              str.add(raw.getString(j, 1));
            }
          }
          sqlResult.add(str.toString());

          if (testcase.getUrl().contains("plan/updatePlanManage")) {
            String jsonInfo = testcase.getJsonInfo();
            JSONObject caseJson = JSONObject.fromObject(jsonInfo);
            String[] value = (String[])str.toArray(new String[str.size()]);
            String planManage = dealPlanManage(caseJson, testcase, dep, value);
            testcase.setJsonInfo(planManage);
          }

          if (!testcase.getUrl().contains("plan/updatePlanManage")) {
            JSONObject json = JSONObject.fromObject(testcase.getJsonInfo());
            if (testcase.getJsonInfo().contains("dependency")) {
              json.getJSONObject("query").discard("dependency");
              json.getJSONObject("query").put(dependency, str.get(0));
              testcase.setJsonInfo(json.toString());
              return true;
            }

            for (int k = 0; k < dep.length; k++) {
              if ((valuetype != null) && (valuetype.equals("array"))) {
                String arrValue = str.toString();
                arrValue = arrValue.substring(1, arrValue.length() - 1);
                json.put(dep[k], arrValue);
              }
              else {
                json.put(dep[k], str.get(0));
              }
            }
            testcase.setJsonInfo(json.toString());
          }
        }
        catch (Exception e) {
          e.printStackTrace();
          return false;
        }
      }
      return true;
    }

    testcase.getDependentController().clearDependency();
    HashMap map = testcase.parseDepency();
    if ((map == null) || (map.isEmpty())) {
      return false;
    }
    boolean result = false;

    Set<Entry<String, String>> set = map.entrySet();
	for (Entry<String, String> entry : set) {
      if (checkIfNumber((String)entry.getKey()))
      {
        Integer Index = Integer.valueOf((String)entry.getKey());
        TestCaseContain depencycase = (TestCaseContain)this.Caseslist.get(Index.intValue() - 1);
        if (depencycase == null) {
          return false;
        }
        result = testcase.runDepency((String)entry.getKey(), (String)entry.getValue(), depencycase);
        if (!result) {
          break;
        }
      }
    }
    testcase.extraOperate(map);
    return result;
  }

  public JSONObject replaceJSON(JSONObject json, String origin, String dest, String[] value) {
    json.discard(origin);
    json.put(dest, value);
    return json;
  }

  public String dealPlanManage(JSONObject json, TestCaseContain testcase, String[] key, String[] value) {
    String jsonInfo = testcase.getJsonInfo();
    JSONObject caseJson = JSONObject.fromObject(jsonInfo);
    int start = jsonInfo.indexOf("[");
    int end = jsonInfo.indexOf("]");
    String formateString = jsonInfo.substring(start + 1, end);
    for (int j = 0; j < key.length; j++) {
      JSONObject newJson = new JSONObject();
      newJson.put("name", key[j]);
      newJson.put("value", value[j]);

      String putString = newJson.toString();
      formateString = formateString + "," + putString;
    }
    caseJson.discard("formData");
    String returnInfo = caseJson.toString();
    int start1 = returnInfo.indexOf("{");
    int end1 = returnInfo.indexOf("}");
    String query = returnInfo.substring(start1 + 1, end1);
    returnInfo = "{\"formData\":[" + formateString + "]," + query + "}";
    return returnInfo;
  }

  private boolean checkIfNumber(String value)
  {
    for (int i = 0; i < 10; i++)
    {
      if (value.contains(String.valueOf(i)))
      {
        return true;
      }
    }
    return false;
  }

  public String getTestcaseFileName(String filePath) {
    Pattern pattern = Pattern.compile("([a-zA-Z0-9\\-_]+.xls)");
    Matcher matcher = pattern.matcher(filePath);
    if (matcher.find()) {
      Pattern pattern1 = Pattern.compile("([a-zA-Z0-9]+)");
      Matcher matcher1 = pattern1.matcher(matcher.group(0).toString());
      if (matcher1.find()) {
        return matcher1.group(0).toString() + ".xls";
      }
    }
    return "";
  }

  public TestCaseContain getTestContain(String caseName, String url, String jsonInfo, String expectInfo, String resultFlag, String dependency, String requestMethod)
  {
    TestCaseContain testcase = null;

    testcase = new CommonLogicContainer(url, jsonInfo, expectInfo, resultFlag, dependency, requestMethod);

    return testcase;
  }

  public String autoRun(String path, String url)
  {
    StringBuffer logoutput = new StringBuffer();
    Map s = new TreeMap();
    ExcelData iter = new ExcelData(path);
    String startTime = "StartTime: " + getCurrentTime();

    this.url = url;
    long startT = System.currentTimeMillis();
    String PathName = getTestcaseFileName(path);
    fLogger.info("=========Test cases of " + PathName + " begin=========\n");
    while (iter.hasNext()) {
      Object[] str = iter.next();
      s = (Map)str[0];
      String tmpUrl = ((String)s.get("url")).toString().trim();

      url = tmpUrl;
      if (url.equalsIgnoreCase("finish"))
      {
        System.out.println("All Cases finished!");
        break;
      }

      String jsonInfo = ((String)s.get("jsonInfo")).toString().trim();
      String expectInfo = ((String)s.get("expectInfo")).toString().trim();
      String resultFlag = ((String)s.get("resultFlag")).toString().trim();
      String dependency = ((String)s.get("dependency")).toString().trim();
      String requestMethod = ((String)s.get("requestMethod")).toString().trim();

      TestCaseContain testcase = getTestContain(PathName, url, jsonInfo, expectInfo, resultFlag, dependency, requestMethod);
      if (testcase == null)
      {
        fLogger.info("unknown excel modal name.");
        logoutput.append("unknown excel modal name.");
        return logoutput.toString();
      }

      testcase.setLogInfo(logoutput);

      putInCaseList(testcase);
    }

    setFilePath(path);
    setlogInfo(logoutput);
    int passNum = runCases();

    String endTime = "EndTime: " + getCurrentTime();
    long endT = System.currentTimeMillis();
    ModifyExcel.modifyCell(this.filePath, 0, 0, 1, startTime);
    ModifyExcel.modifyCell(this.filePath, 0, 0, 2, endTime);
    ModifyExcel.modifyCell(this.filePath, 0, 0, 3, getLastTime(endT - startT));
    ModifyExcel.modifyCell(this.filePath, 0, 1, 5, String.valueOf(passNum));
    ModifyExcel.modifyCell(this.filePath, 0, 1, 6, String.valueOf(this.Caseslist.size() - passNum));
    ModifyExcel.modifyCell(this.filePath, 0, 1, 8, String.valueOf(this.Caseslist.size()));
    fLogger.info("=========test cases end=========\n\n\n\n");
    return logoutput.toString();
  }

  public String getCurrentTime() {
    Date date = new Date();
    SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String time = matter.format(date);
    return time;
  }
  public String getLastTime(long time) {
    String str = "LastTime:";
    long msec = time % 1000L;
    long sec = time / 1000L % 60L;
    long min = time / 1000L / 60L % 60L;
    long hr = time / 1000L / 60L / 60L % 24L;
    long d = time / 1000L / 60L / 60L / 24L % 30L;
    str = str + String.valueOf(d) + "d " + 
      String.valueOf(hr) + "hr " + 
      String.valueOf(min) + "min " + 
      String.valueOf(sec) + "sec " + 
      String.valueOf(msec) + "msec ";
    return str;
  }

  public String getExecSql(JSONObject json, String action, ArrayList<String> sqlResult) {
    String tablename = json.getString("database");
    String expression = json.containsKey("expression") ? json.getString("expression") : null;
    String column = json.getString("column");
    String[] condition = json.getString("condition").split(",");
    String[] value = json.getString("value").split(",");
    String sql = action + column + " from " + tablename + " where ";
    if (json.containsKey("action")) {
      action = json.getString("action") + " ";
    }

    if (json.containsKey("deCode")) {
      String tmp = (String)json.get("deCode");
      int i = Integer.parseInt(tmp);
      value[0] = ((String)sqlResult.get(i - 1));
      value[0] = value[0].replaceAll("\\[([^\\]]*)\\]", "$1");
    }

    if (action == "select ") {
      if (json.toString().contains("parse")) {
        int code = Integer.parseInt(value[0]);
        sql = sql + condition[0] + " = " + code;
      }
      else
      {
        sql = addCondition(sql, condition, expression, value);
      }
    }

    if (action == "delete ") {
      sql = action + "from" + tablename + " where " + condition + " = " + value;
    }
    return sql;
  }

  public String addCondition(String sql, String[] condition, String expression, String[] value) {
    for (int i = 0; i < condition.length; i++) {
      if (i != 0) {
        sql = sql + " and ";
      }
      if (expression == null) {
        expression = "like";
      }
      sql = sql + condition[i] + " " + expression + " " + "\"" + value[i] + "\"";
    }

    return sql;
  }

  public String matchUrl(String url, String replaceUrl) {
    if (url.equals("finish")) {
      return url;
    }
    String[] start = url.split("//");
    int end = start[1].indexOf("/");

    start[1] = (replaceUrl + start[1].substring(end, start[1].length()));

    return start[0] + "//" + start[1];
  }
}



package common;

import impl.RESTClientImpl;

import java.util.HashMap;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import rest.RESTClientUtils;

public abstract class TestCaseContain {
	private static Logger fLogger = Logger.getLogger(TestCaseContain.class);
	private static String tokenID = "";
	private String url;
	private String jsonInfo;
	private String queryInfo;
	private String expectInfo;
	private String resultFlag;
	private String requestMethod;
	private String dependentInfo;
	private String resultDataInfo;
	private StringBuffer logInfo;
	protected Dependent dependentController;
	
	public static Logger getfLogger() {
		return fLogger;
	}
	public static void setfLogger(Logger fLogger) {
		TestCaseContain.fLogger = fLogger;
	}
	public static String getTokenID() {
		return tokenID;
	}
	public static void setTokenID(String tokenID) {
		TestCaseContain.tokenID = tokenID;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getJsonInfo() {
		return jsonInfo;
	}
	public void setJsonInfo(String jsonInfo) {
		this.jsonInfo = jsonInfo;
	}
	public String getQueryInfo() {
		return queryInfo;
	}
	public void setQueryInfo(String queryInfo) {
		this.queryInfo = queryInfo;
	}
	public String getExpectInfo() {
		return expectInfo;
	}
	public void setExpectInfo(String expectInfo) {
		this.expectInfo = expectInfo;
	}
	public String getResultFlag() {
		return resultFlag;
	}
	public void setResultFlag(String resultFlag) {
		this.resultFlag = resultFlag;
	}
	public String getRequestMethod() {
		return requestMethod;
	}
	public void setRequestMethod(String requestMethod) {
		this.requestMethod = requestMethod;
	}
	public String getDependentInfo() {
		return dependentInfo;
	}
	public void setDependentInfo(String dependentInfo) {
		this.dependentInfo = dependentInfo;
	}
	public String getResultDataInfo() {
		return resultDataInfo;
	}
	public void setResultDataInfo(String resultDataInfo) {
		this.resultDataInfo = resultDataInfo;
	}
	public StringBuffer getLogInfo() {
		return logInfo;
	}
	public void setLogInfo(StringBuffer logInfo) {
		this.logInfo = logInfo;
	}
	public Dependent getDependentController() {
		return dependentController;
	}
	public void setDependentController(Dependent dependentController) {
		this.dependentController = dependentController;
	}
	
	public TestCaseContain(String url,String jsonInfo,String expectInfo,String resultflag,String dependentInfo,String requestMethod ){
		this.url = url;
		this.jsonInfo = jsonInfo;
		this.expectInfo = expectInfo;
		this.resultFlag = resultflag;
		this.requestMethod = requestMethod;
		this.dependentInfo =dependentInfo;
		
		this.resultDataInfo = "";
		this.logInfo = null;
		this.dependentController = null;
	}
	
	public boolean runCase(){
		RESTClientImpl restClient = new RESTClientImpl();
		restClient.setToken(tokenID);
		String temp_jsonInfo = "";
		
		try {
			temp_jsonInfo = setTokenInfo(this.jsonInfo);
			HttpResponse result = restClient.sendMsg(this.requestMethod,
					this.url, temp_jsonInfo);
			if ((this.url.contains("completeDefect"))
					|| (this.url.contains("rejectOpreateTicket"))) {
				Thread.sleep(2000L);
				System.out.println("\n\n\n");
			}
			if (result.toString().contains("200 OK")) {
				String str_result = EntityUtils.toString(result.getEntity(),
						"UTF-8");
				return checkResult(str_result, this.requestMethod);
			}
		} catch (Throwable e) {
			fLogger.info("rest API " + this.url + "測試出錯" + e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean checkResult(String str_result,String requestMethod){
		if(requestMethod.equalsIgnoreCase("get")){
			if(str_result !=null){
				return true;
			}
			
			return false;
		}
		
		if((this.url.contains("listSingleDutyEvent"))&&(str_result.contains("deId"))&&(str_result.contains("odId"))){
			return true;
		}
		
		boolean resFlag = false;
		String Info ="";
		HashMap resMap = new HashMap();
		if((str_result !=null)&&(!"".equals(str_result))){
			resMap = RESTClientUtils.parseJSONtoMAP(str_result);
			String s_value = (String)resMap.get("success");
			String d_value = (String)resMap.get("data");
			String p_value = (String)resMap.get("params");
			
			if(s_value.equals("false")){
				System.out.println("url: "+this.url+'\n');
				System.out.println("result:"+str_result+'\n');
			}
			
			this.resultDataInfo = d_value;
			if(this.url.contains("system/login")){
				tokenID = StringUtils.substringBetween(p_value,"[\"", 
				          "\"]");
			}
			
			if(this.resultFlag.equalsIgnoreCase(s_value)){
				Info = "rest API" + this.url + "预期调用与否一致";
				this.logInfo.append(Info);
				this.logInfo.append("\n");
				resFlag = true;
		        if ((("true".equalsIgnoreCase(s_value)) && 
		                (d_value
		                .contains(this.expectInfo))) || 
		                ("false".equalsIgnoreCase(s_value))) {
		                resFlag = true;
		                fLogger.info("rest API " + this.url + 
		                  " 预期返回值正确");
		              } else {
		                Info = "rest API " + this.url + " 返回值错误" + str_result;
		                this.logInfo.append(Info);
		                this.logInfo.append("\n");
		                fLogger.info(Info);
		              }
			}else {
		        Info = "rest API " + this.url + " 预期调用成功与否不一致" + str_result;
		        this.logInfo.append(Info);
		        this.logInfo.append("\n");
		        fLogger.info(Info);
		      }
		}
		else {
		      Info = "rest API " + this.url + " 返回值为空串" + str_result;
		      this.logInfo.append(Info);
		      this.logInfo.append("\n");
		      fLogger.info(Info);
		    }
		    return resFlag;
	}
	
	public abstract boolean runDepency(String paramString1,String paramString2,TestCaseContain paramTestCaseContain);
	
	public abstract void extraOperate(HashMap<String,String> paramHashMap);
	
	public HashMap<String,String> parseDepency(){
		if(this.dependentInfo.isEmpty()){
			return null;
		}
		return RESTClientUtils.parseJSONtoMAP(this.dependentInfo);
	}
	
	public String toString() {
		 return "url:" + this.url + "; jsonInfo:" + this.jsonInfo + "; expectInfo:" + this.expectInfo + "; resultFlag:" + 
			      this.resultFlag + "; requestMethod:" + this.requestMethod + "; dependentInfo:" + this.dependentInfo + 
			      "; dependentController:" + this.dependentController.toString();
	}
	
	public String setTokenInfo(String jsonInfo){
		HashMap temp_jsonMap = RESTClientUtils.parseJSONtoMAP(jsonInfo);
		if(this.url.contains("staff/saveStaff")){
			temp_jsonMap.put("stationid", "auto_test_station");
		}
		
		temp_jsonMap.put("token720", tokenID);
		String temp_jsonInfo = JSONObject.fromObject(temp_jsonMap).toString();
		return temp_jsonInfo;
	}
}


package commonlogic;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import net.sf.json.JSONObject;
import common.Dependent;
import common.TestCaseContain;

public class CommonLogicContainer extends TestCaseContain
{
  public CommonLogicContainer(String url, String jsonInfo, String expectInfo, String resultflag, String dependentInfo, String requestMethod)
  {
    super(url, jsonInfo, expectInfo, resultflag, dependentInfo, requestMethod);

    this.dependentController = new Dependent();
  }

  public boolean runDepency(String depencyKey, String depencyValue, TestCaseContain depencyCase)
  {
    String[] arr = depencyValue.split(",");
    this.dependentController.setKey(arr);
    String resultInfo = depencyCase.getResultDataInfo();
    if (resultInfo.isEmpty()) return false;
    this.dependentController.addDependencyValue(resultInfo);
    return true;
  }

  public void extraOperate(HashMap<String, String> map)
  {
	  Set<Entry<String, String>> set = map.entrySet();  
		for(Entry<String,String> entry:set){
      if (((String)entry.getKey()).equalsIgnoreCase("update"))
      {
        this.dependentController.updatekeys((String)entry.getValue());
      }

    }

    if ((getRequestMethod().equalsIgnoreCase("post")) || (getRequestMethod().equalsIgnoreCase("put"))) {
      JSONObject jsonInfo = JSONObject.fromObject(getJsonInfo());
      if (jsonInfo.containsKey("query")) {
        String query = jsonInfo.getString("query");
        JSONObject jsonInfo1 = JSONObject.fromObject(query);
        jsonInfo1.discard("dependency");
        if (query.contains("dependency")) {
          query = this.dependentController.setJsonDepencyInfo(jsonInfo1.toString());
        }
        jsonInfo.discard("query");
        jsonInfo.put("query", query);
        setJsonInfo(jsonInfo.toString());
      }
      else {
        setJsonInfo(this.dependentController.setJsonDepencyInfo(getJsonInfo()));
      }
    }
  }
}


package impl;

import intf.RESTClientInt;

import java.io.IOException;
import java.net.URI;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

public class RESTClientImpl implements RESTClientInt{
	private HttpClient client;
	private String token;
	
	public void setToken(String token){
		this.token = token;
	}
	
	public HttpResponse sendMsg(String method,String path,String input) throws IOException{
		if(method.equalsIgnoreCase("post")){
			return post(path,input);
		}
		if(method.equalsIgnoreCase("get")){
			return post(path,input);
		}
		if(method.equalsIgnoreCase("put")){
			return post(path,input);
		}
		if(method.equalsIgnoreCase("delete")){
			return post(path,input);
		}
		return null;
	}
	
	
	public HttpResponse post(String path, String input) throws IOException
	  {
	    HttpResponse result = callWithJSON(path, "POST", input);
	    return result;
	  }

	  public HttpResponse get(String path, String input) throws IOException
	  {
	    return callWithJSON(path, "GET", input);
	  }

	  public HttpResponse put(String path, String input) throws IOException
	  {
	    return callWithJSON(path, "PUT", input);
	  }

	  public HttpResponse delete(String path, String input) throws IOException
	  {
	    return callWithJSON(path, "DELETE", input);
	  }
	  
	  
	  public HttpResponse callWithJSON(String path,String method,String input) throws IOException,UnsupportedOperationException{
		  String url = path;
		  HttpRequestBase request = null;
		  if (StringUtils.equalsIgnoreCase(method, "POST"))
		    {
		      request = new HttpPost();
		    }
		    else if (StringUtils.equalsIgnoreCase(method, "GET"))
		    {
		      request = new HttpGet();
		    }
		    else if (StringUtils.equalsIgnoreCase(method, "DELETE"))
		    {
		      request = new HttpDelete();
		    }
		    else if (StringUtils.equalsIgnoreCase(method, "PUT"))
		    {
		      request = new HttpPut();
		    }
		    else
		    {
		      throw new UnsupportedOperationException("It can not support the http method: " + method + "! Only support " + "POST" + ", " + 
		        "GET" + ", " + "PUT" + ", " + "DELETE");
		    }
		  request.setURI(URI.create(url));
		  
		  BasicHeader bheader = new BasicHeader("Content-Type", "application/json;charset=UTF-8");
		  request.setHeader(bheader);
		  BasicHeader basich = new BasicHeader("Accept", "application/json");
		  request.setHeader(basich);
		  
		  request.addHeader("cookie", "token720=123456;loginType720=NO_SSO");
		  if ((input != null) && ((request instanceof HttpEntityEnclosingRequestBase)))
		    {
		      StringEntity entity = new StringEntity(input, "utf-8");
		      ((HttpEntityEnclosingRequestBase)request).setEntity(entity);
		    }
		  
		  this.client = new DefaultHttpClient();
		    return this.client.execute(request);
	  }
}



package intf;

import java.io.IOException;

import org.apache.http.HttpResponse;

public abstract interface RESTClientInt {
   public abstract HttpResponse post(String paramString1,String paramString2) throws IOException;
   
   public abstract HttpResponse get(String paramString1,String paramString2) throws IOException;

   public abstract HttpResponse put(String paramString1,String paramString2) throws IOException;
   
   public abstract HttpResponse delete(String paramString1,String paramString2) throws IOException;
}



package rest;

import java.util.HashMap;
import java.util.Iterator;

import net.sf.json.JSONObject;

public class RESTClientUtils {
		public static HashMap<String,String> parseJSONtoMAP(String respInfo){
			HashMap map = new HashMap();
			JSONObject jsonInfo = JSONObject.fromObject(respInfo);
			Iterator keys = jsonInfo.keys();
			while(keys.hasNext()){
				String key = (String)keys.next();
				String value = jsonInfo.getString(key).toString();
				map.put(key,value);
			}
			return map;
		}
}




package type;

public class Test
{
  public static TestObject to;

  public static TestObject getTo()
  {
    return to;
  }

  public static void setTo(TestObject to) {
    to = to;
  }

  public static boolean is710() {
    return to == TestObject.TYPE_710;
  }

  public static boolean is720() {
    return to == TestObject.TYPE_720;
  }
}


package type;

public enum TestObject
{
  TYPE_710, TYPE_720;
}



package util;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.apache.tools.ant.types.EnumeratedAttribute;

public class AntExecSql {
	public static void sqlRun(String sqlin, String sqlout, String sqlConn,
			String url) throws Exception {
		try {
			String sqlUrl;
			if (sqlConn.equalsIgnoreCase("station")) {
				sqlUrl = "jdbc:mysql://"
						+ url
						+ ":3309/epmsstation?characterEncoding=UTF-8&amp;useUnicode=true";
			} else {
				sqlUrl = "jdbc:mysql://"
						+ url
						+ ":3308/epmsgroup?characterEncoding=UTF-8&amp;useUnicode=true";

			}
			SQLExec sqlExec = new SQLExec();
			sqlExec.setDriver("com.mysql.jdbc.Driver");
			sqlExec.setUrl(sqlUrl);
			sqlExec.setUserid("system");
			sqlExec.setPassword("Hwsystem@com");

			sqlExec.setSrc(new File(sqlin));

			sqlExec.setOnerror((SQLExec.OnError) EnumeratedAttribute
					.getInstance(SQLExec.OnError.class, "abort"));
			sqlExec.setPrint(true);
			sqlExec.setOutput(new File(sqlout));
			sqlExec.setProject(new Project());
			sqlExec.execute();
		} catch (Exception e) {
			throw e;
		}
	}
	
	 public static void main(String[] args) throws Exception
	  {
	    sqlRun("sql\run.sql", "", args[2], args[3]);
	  }
}




package util;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExcelData {
	private Workbook book = null;
	private Sheet sheet = null;
	private int rowNum = 0;
	private int curRowNo = 0;
	private int columnNum = 0;
	private String[] columnnName;
	private String sheetname;
	
	public ExcelData(String filepath) {
		try {
			String file = filepath;
			this.book = Workbook.getWorkbook(new File(file));
			this.sheet = this.book.getSheet(1);
			this.rowNum = this.sheet.getRows();
			Cell[] c = this.sheet.getRow(0);
			this.columnNum = c.length;
			this.columnnName = new String[c.length];
			for (int i = 0; i < c.length; i++) {
				this.columnnName[i] = c[i].getContents().toString();
			}
			this.curRowNo += 1;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public void changeCell(int row, int col, String value) {
		try {
			WritableWorkbook wwb = Workbook.createWorkbook(new File(
					"D:\\demo.xls"), this.book);
			WritableSheet ws = wwb.getSheet(this.sheetname);
			WritableCell wc = ws.getWritableCell(row, col);
			Label label = (Label) wc;
			label.setString(value);
			ws.addCell(wc);
			wwb.write();
			wwb.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
	}
	
	public boolean hasNext() {
		if ((this.rowNum == 0) || (this.curRowNo >= this.rowNum)) {
			try {
				this.book.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}
	
	public Object[] next()
	{
		Cell[] c = this.sheet.getRow(this.curRowNo);
		Map s = new TreeMap();
		for (int i = 0; i <this.columnNum;i++){
			String temp = "";
			try {
				temp = c[i].getContents().toString();
			} catch (ArrayIndexOutOfBoundsException ex) {
				temp = "";
			}
			s.put(this.columnnName[i], temp);
		}
		
		Object[] r = new Object[1];
		r[0]=s;
		this.curRowNo +=1;
		return r;
	}
	
	
	public static void main(String[] args) {
		ExcelData exceldata = new ExcelData(".\report\\caseAll\birtReport_Report_2016-06-01_17-38-15.xls");
	}
	
}



package util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;

public class Log4jUtils
{
  public static void configLog()
  {
    String configFileName = "./src/log4j.properties";
    Properties props = new Properties();
    try
    {
      FileInputStream istream = new FileInputStream(configFileName);
      props.load(istream);
      istream.close();
    }
    catch (IOException e)
    {
      System.err.println("Could not read configuration file [" + configFileName + "].");
      e.printStackTrace();
      return;
    }
    PropertyConfigurator.configure(props);
  }
}



package util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.CellView;
import jxl.Range;

public class ManagerExcel
{
  private ReadExcel re;
  private WriteExcel we;
  private List<String> readFiles;
  private int curr;
  public static long casesStartTimer;
  public static long casesEndTimer;
  public static String casesStartTime;
  public static String casesEndTime;

  public ManagerExcel()
  {
  }

  public ManagerExcel(List<String> readFiles, String write)
  {
    this.readFiles = readFiles;
    this.curr = 0;
    this.re = new ReadExcel((String)readFiles.get(this.curr));
    this.we = new WriteExcel(write);
  }

  public boolean readNextExcel()
  {
    if (this.readFiles.size() - 1 == this.curr)
    {
      return false;
    }
    this.re = new ReadExcel((String)this.readFiles.get(++this.curr));

    return true;
  }

  public ManagerExcel(ReadExcel re, WriteExcel we) {
    this.re = re;
    this.we = we;
  }

  public void copy() {
    int sheet = 0;
    String[] sheetname = { "结果统计", "测试结果详细信息" };

    for (int i = 0; i < sheetname.length; i++) {
      this.we.createSheet(sheetname[i], i);
    }
    do
    {
      copy(0, sheet++);
      if (sheet == 2)
        addResultCol();
    }
    while (readNextExcel());
    close();
  }

  public void copy(int srcsheet, int dessheet) {
    this.re.setSheet(srcsheet);
    this.we.setSheet(dessheet);
    int rows = this.re.getRowNum();
    int cols = this.re.getColNum();
    for (int i = 0; i < rows; i++) {
      CellView list = this.re.getRowView(i);
      this.we.setRowView(i, list);
    }
    for (int j = 0; j < cols; j++) {
      CellView list = this.re.getColumnView(j);
      this.we.setColumnView(j, list);
    }
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        List list = this.re.readCell(i, j);
        this.we.writeCell(i, j, list);
      }
    }
    mergeCell();
  }

  public void merge() {
    this.re.setSheet(0);
    this.we.setSheet(0);
    List listReport = getReportFileList();
    int rows = this.re.getRowNum();
    int cols = this.re.getColNum();
    for (int i = 0; i < rows; i++) {
      CellView list = this.re.getRowView(i);
      this.we.setRowView(i, list);
    }
    for (int j = 0; j < cols; j++) {
      CellView list = this.re.getColumnView(j);
      this.we.setColumnView(j, list);
    }
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < cols; j++) {
        List list = this.re.readCell(i, j);
        this.we.writeCell(i, j, list);
      }
    }
    for (int k = 0; k < listReport.size(); k++) {
      for (int i = 5; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
          List list = this.re.readCell(i, j);
          if ((i == 5) && (j == 0))
            list.set(2, RegularUtils.getReportFileName((String)listReport.get(k)));
          this.we.writeCell(i + k * 4, j, list);
        }
      }
    }
    mergeReportCell(listReport.size());
    for (int i = 0; i < listReport.size(); i++) {
      this.re = new ReadExcel((String)listReport.get(i));
      copy(1, i + 1);
    }
    close();
    modifyReport();
  }

  public void modifyReport() {
    int passed = 0;
    int failed = 0;
    int blocked = 0;
    int total = 0;

    List listReport = getReportFileList();
    String filePath = ".\\report\\caseAll\\Summary.xls";
    ModifyExcel me = new ModifyExcel(filePath, filePath);
    me.setSheet(0);

    for (int i = 0; i < listReport.size(); i++) {
      this.re = new ReadExcel((String)listReport.get(i));
      this.re.setSheet(0);
      me.modifycell(2, 5 + 4 * i, (String)this.re.readCell(5, 1).get(2));
      me.modifycell(2, 6 + 4 * i, (String)this.re.readCell(6, 1).get(2));
      me.modifycell(2, 7 + 4 * i, (String)this.re.readCell(7, 1).get(2));
      me.modifycell(2, 8 + 4 * i, (String)this.re.readCell(8, 1).get(2));

      if (!((String)listReport.get(i)).contains("0Summary")) {
        passed += Integer.parseInt((String)this.re.readCell(5, 1).get(2));
        failed += Integer.parseInt((String)this.re.readCell(6, 1).get(2));
        blocked += Integer.parseInt((String)this.re.readCell(7, 1).get(2));
        total += Integer.parseInt((String)this.re.readCell(8, 1).get(2));
      }

    }

    this.re = new ReadExcel((String)listReport.get(0));
    this.re.setSheet(0);

    me.modifycell(0, 1, casesStartTime);
    me.modifycell(0, 2, casesEndTime);
    me.modifycell(0, 3, getLastTimeEXCEL(casesEndTimer - casesStartTimer));

    me.modifycell(0, 5, "汇总");
    me.modifycell(2, 5, passed);
    me.modifycell(2, 6, failed);
    me.modifycell(2, 7, blocked);
    me.modifycell(2, 8, total);

    me.close();
  }

  public void mergeReports() {
    List listReport = getReportFileList();
    this.re = new ReadExcel(".\\template\\Summary.xls");
    this.we = new WriteExcel(".\\report\\caseAll\\Summary.xls");
    this.we.createSheet("结果统计", 0);
    for (int i = 1; i < listReport.size() + 1; i++)
      this.we.createSheet(RegularUtils.getReportFileName((String)listReport.get(i - 1)), i);
    merge();
  }
  public List<String> getReportFileList() {
    String report = ".\\report\\caseAll\\";
    List list = new ArrayList();
    File file = new File(report);
    String[] files = file.list();
    for (int i = 0; i < files.length; i++) {
      if ((files[i].contains(".xls")) && (!files[i].equals("Summary.xls"))) {
        list.add(report + files[i]);
      }
    }
    return list;
  }
  public void mergeCell() {
    Range[] range = this.re.getMergedCells();
    for (int i = 0; i < range.length; i++)
      this.we.mergeCells(
        range[i].getTopLeft().getColumn(), 
        range[i].getTopLeft().getRow(), 
        range[i].getBottomRight().getColumn(), 
        range[i].getBottomRight().getRow());
  }

  public void mergeReportCell(int loop)
  {
    mergeCell();
    int leftColumn = 0; int leftRow = 9; int rightColumn = 0; int rightleftRow = 12;
    for (int i = 0; i < loop - 1; i++)
      this.we.mergeCells(
        leftColumn, 
        leftRow + i * 4, 
        rightColumn, 
        rightleftRow + i * 4);
  }

  public void addResultCol()
  {
    int rows = this.re.getRowNum();
    this.we.writeCell(0, 10, this.re.addLabelCell("passFlag"));

    for (int i = 1; i < rows - 1; i++) {
      this.we.writeCell(i, 10, this.re.addLabelCell("passed"));
    }

    this.we.writeCell(rows - 1, 10, this.re.addLabelCell(""));
  }
  public void close() {
    this.re.close();
    this.we.close();
  }
  public ReadExcel getReadExcel() {
    return this.re;
  }
  public void setReadExcel(ReadExcel re) {
    this.re = re;
  }
  public WriteExcel getWriteExcel() {
    return this.we;
  }
  public void setWriteExcel(WriteExcel we) {
    this.we = we;
  }

  public String getLastTimeEXCEL(long time) {
    String str = "LastTime:";
    long msec = time % 1000L;
    long sec = time / 1000L % 60L;
    long min = time / 1000L / 60L % 60L;
    long hr = time / 1000L / 60L / 60L % 24L;
    long d = time / 1000L / 60L / 60L / 24L % 30L;
    str = str + String.valueOf(d) + "d " + 
      String.valueOf(hr) + "hr " + 
      String.valueOf(min) + "min " + 
      String.valueOf(sec) + "sec " + 
      String.valueOf(msec) + "msec ";
    return str;
  }

  public static String getCurrentTimeEXCEL() {
    Date date = new Date();
    SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String time = matter.format(date);
    return time;
  }
}



package util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import jxl.CellType;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ModifyExcel
{
  private Workbook rwb;
  private WritableWorkbook wwb;
  private WritableSheet ws;

  public ModifyExcel(String readFileName, String writeFileName)
  {
    try
    {
      this.rwb = Workbook.getWorkbook(new File(readFileName));
      this.wwb = Workbook.createWorkbook(new File(writeFileName), this.rwb);
    } catch (BiffException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void setSheet(int sheet) { this.ws = this.wwb.getSheet(sheet); }

  public static void modifyCell(String fileName, int sheet, int row, int col, Object value)
  {
    try
    {
      Workbook rwb = Workbook.getWorkbook(new File(fileName));
      WritableWorkbook wwb = Workbook.createWorkbook(new File(fileName), rwb);
      WritableSheet ws = wwb.getSheet(sheet);
      WritableCell cell = ws.getWritableCell(row, col);

      if (cell.getType() == CellType.EMPTY) {
        value = null;
      } else if (cell.getType() == CellType.LABEL) {
        Label label = (Label)cell;
        label.setString((String)value);
      } else if (cell.getType() == CellType.BOOLEAN) {
        jxl.write.Boolean label = (jxl.write.Boolean)cell;
        label.setValue(((java.lang.Boolean)value).booleanValue());
      } else if (cell.getType() == CellType.NUMBER) {
        Number label = (Number)cell;
        label.setValue(((Double)value).doubleValue());
      }
      else if (cell.getType() == CellType.DATE) {
        Date label = (Date)cell;
        label.setDate(((Integer)value).intValue());
      }

      wwb.write();
      wwb.close();
      rwb.close();
    }
    catch (BiffException e1) {
      e1.printStackTrace();
    }
    catch (IOException e1) {
      e1.printStackTrace();
    }
    catch (WriteException e) {
      e.printStackTrace();
    }
  }

  public void modifycell(int row, int col, Object value)
  {
    WritableCell cell = this.ws.getWritableCell(row, col);

    if (cell.getType() == CellType.EMPTY) {
      value = null;
    } else if (cell.getType() == CellType.LABEL) {
      Label label = (Label)cell;
      label.setString(value.toString());
      
    } else if (cell.getType() == CellType.BOOLEAN) {
      jxl.write.Boolean label = (jxl.write.Boolean)cell;
      label.setValue(((java.lang.Boolean)value).booleanValue());
    } else if (cell.getType() == CellType.NUMBER) {
      Number label = (Number)cell;
      label.setValue(((Double)value).doubleValue());
    }
    else if (cell.getType() == CellType.DATE) {
      Date label = (Date)cell;
      label.setDate(((Integer)value).intValue());
    }
  }

  public void close()
  {
    try {
      this.wwb.write();
      this.wwb.close();
      this.rwb.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (WriteException e) {
      e.printStackTrace();
    }
  }
}




package util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import jxl.BooleanCell;
import jxl.Cell;
import jxl.CellType;
import jxl.CellView;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Range;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableWorkbook;

public class ReadExcel
{
  private Workbook rwb;
  private WritableWorkbook wwb;
  private Sheet st;

  public ReadExcel(String filePath)
  {
    try
    {
      InputStream is = new FileInputStream(filePath);
      this.rwb = Workbook.getWorkbook(is);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public CellView getRowView(int row) { return this.st.getRowView(row); }

  public CellView getColumnView(int col) {
    return this.st.getColumnView(col);
  }
  public Range[] getMergedCells() {
    return this.st.getMergedCells();
  }

  public List addLabelCell(String str) {
    Cell cell = this.st.getCell(1, 0);
    List list = new ArrayList();
    list.add(CellType.LABEL);
    list.add(cell.getCellFormat());
    list.add(str);

    return list;
  }
  public List readCell(int row, int col) {
    List list = new ArrayList();
    try
    {
      Cell cell = this.st.getCell(col, row);

      Object value = cell.getContents();

      list.add(cell.getType());
      list.add(cell.getCellFormat());
      if (cell.getType() == CellType.EMPTY) {
        value = null;
      } else if (cell.getType() == CellType.LABEL) {
        LabelCell labelc00 = (LabelCell)cell;
        value = labelc00.getString();
      } else if (cell.getType() == CellType.BOOLEAN) {
        BooleanCell labelB = (BooleanCell)cell;
        value = Boolean.valueOf(labelB.getValue());
      } else if (cell.getType() == CellType.NUMBER) {
        NumberCell labelN = (NumberCell)cell;
        value = Double.valueOf(labelN.getValue());
      }
      else if (cell.getType() == CellType.DATE) {
        DateCell labelD = (DateCell)cell;
        value = labelD.getDate();
      }
      list.add(value);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return list;
  }

  public int getRowNum() {
    return this.st.getRows();
  }
  public void setSheet(int sheet) {
    this.st = this.rwb.getSheet(sheet);
  }
  public int getColNum() {
    return this.st.getColumns();
  }
  public void close() {
    this.rwb.close();
  }
}



package util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularUtils
{
  public static String getFilePath(String filename)
  {
    String[] names = filename.split("\\\\");
    String path = "";
    for (int i = 0; i < names.length - 2; i++)
      path = path + names[i] + "\\";
    path = path.substring(0, path.length() - 1);
    return path;
  }

  public static String getFileName(String filename)
  {
    String[] names = filename.split("\\\\");
    String file = names[(names.length - 1)].split("\\.")[0];
    return file;
  }
  public static String getTestcaseFileName(String filePath) {
    Pattern pattern = Pattern.compile("([a-zA-Z0-9\\-_]+.xls)");
    Matcher matcher = pattern.matcher(filePath);
    if (matcher.find()) {
      Pattern pattern1 = Pattern.compile("([a-zA-Z0-9]+)");
      Matcher matcher1 = pattern1.matcher(matcher.group(0).toString());
      if (matcher1.find()) {
        return matcher1.group(0).toString() + ".xls";
      }
    }
    return "";
  }
  public static String getReportFileName(String filePath) {
    Pattern pattern = Pattern.compile("([a-zA-Z0-9\\-_]+.xls)");
    Matcher matcher = pattern.matcher(filePath);
    if (matcher.find()) {
      Pattern pattern1 = Pattern.compile("([a-zA-Z0-9]+)");
      Matcher matcher1 = pattern1.matcher(matcher.group(0).toString());
      if (matcher1.find()) {
        return matcher1.group(0).toString();
      }
    }
    return "";
  }
}



package util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import jxl.CellType;
import jxl.CellView;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.format.Font;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class WriteExcel
{
  private Workbook rwb;
  private WritableWorkbook wwb;
  private WritableSheet ws;

  public WriteExcel(String filePath)
  {
    try
    {
      this.wwb = Workbook.createWorkbook(new File(filePath));
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public WritableCellFormat getWritableCellFormat(CellFormat cellFormat) { WritableCellFormat wcf = new WritableCellFormat();
    try {
      if (cellFormat != null) {
        if (cellFormat.getBackgroundColour().equals(Colour.DEFAULT_BACKGROUND)) {
          wcf.setBackground(Colour.WHITE);
        }
        else
          wcf.setBackground(cellFormat.getBackgroundColour());
        if (cellFormat.getFont().getColour().equals(Colour.WHITE)) {
          WritableFont wf_color = new WritableFont(WritableFont.ARIAL, cellFormat.getFont().getPointSize(), WritableFont.BOLD, false, cellFormat.getFont().getUnderlineStyle(), cellFormat.getFont().getColour());
          wcf.setFont(wf_color);
        }

        wcf.setWrap(cellFormat.getWrap());
        wcf.setAlignment(cellFormat.getAlignment());
        wcf.setVerticalAlignment(cellFormat.getVerticalAlignment());
        wcf.setBorder(Border.ALL, BorderLineStyle.THIN, cellFormat.getBorderColour(Border.ALL));
      }
    } catch (WriteException e) {
      e.printStackTrace();
    }
    return wcf; }

  public WritableSheet createSheet(String name, int sheet) {
    return this.wwb.createSheet(name, sheet);
  }

  public void writeCell(int row, int col, List list)
  {
    try
    {
      CellType type = (CellType)list.get(0);

      CellFormat cellFormat = (CellFormat)list.get(1);
      WritableCellFormat wcf = getWritableCellFormat(cellFormat);
      Object value = list.get(2);
      if (type.equals(CellType.EMPTY))
      {
        Label label = new Label(col, row, "");
        wcf.setBorder(Border.ALL, BorderLineStyle.THIN);
        label.setCellFormat(wcf);
        this.ws.addCell(label);
      } else if (type.equals(CellType.LABEL))
      {
        Label label = new Label(col, row, (String)value);
        if (cellFormat != null) {
          label.setCellFormat(wcf);
        }
        this.ws.addCell(label);
      } else if (type.equals(CellType.BOOLEAN))
      {
        jxl.write.Boolean label = new jxl.write.Boolean(col, row, ((java.lang.Boolean)value).booleanValue());
        if (cellFormat != null) {
          label.setCellFormat(wcf);
        }
        this.ws.addCell(label);
      } else if (type.equals(CellType.NUMBER))
      {
        Number label = new Number(col, row, ((Double)value).doubleValue());
        if (cellFormat != null) {
          label.setCellFormat(wcf);
        }
        this.ws.addCell(label);
      } else if (type.equals(CellType.DATE))
      {
        DateTime label = new DateTime(col, row, (Date)value);
        if (cellFormat != null) {
          label.setCellFormat(wcf);
        }
        this.ws.addCell(label);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void setRowView(int row, CellView cv) {
    try { this.ws.setRowView(row, cv);
    } catch (RowsExceededException e) {
      e.printStackTrace();
    }
  }

  public void setColumnView(int col, CellView cv) { this.ws.setColumnView(col, cv); }

  public void mergeCells(int col1, int row1, int col2, int row2) {
    try {
      this.ws.mergeCells(col1, row1, col2, row2);
    } catch (RowsExceededException e) {
      e.printStackTrace();
    } catch (WriteException e) {
      e.printStackTrace();
    }
  }

  public void modifyCell(int row, int col, List list)
  {
    WritableCell wc = this.ws.getWritableCell(row, col);

    CellType type = (CellType)list.get(0);
    Object value = list.get(1);
    if (!type.equals(CellType.EMPTY))
    {
      if (type == CellType.LABEL) {
        Label label = (Label)wc;
        label.setString((String)value);
      } else if (type == CellType.BOOLEAN) {
        jxl.write.Boolean label = (jxl.write.Boolean)wc;
        label.setValue(((java.lang.Boolean)value).booleanValue());
      } else if (type == CellType.NUMBER) {
        Number label = (Number)wc;
        label.setValue(((Double)value).doubleValue());
      } else if (type == CellType.DATE) {
        DateTime label = (DateTime)wc;
        label.setDate((Date)value);
      }
    }
  }

  public void setSheet(int sheet)
  {
    this.ws = this.wwb.getSheet(sheet);
  }

  public void close()
  {
    try
    {
      this.wwb.write();
      this.wwb.close();
    } catch (WriteException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



package utils.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.log4j.Logger;

public class DBAccess {
	private static Logger fLogger = Logger.getLogger(DBAccess.class);
	static boolean PLUGINLOG = false;
	private boolean DEBUG;
	private static final String DBTYPE = "DBType";
	private static final String SERVERNAME = "ServerName";
	private static final String PORT = "Port";
	private static final String USER = "User";
	private static final String PWD = "Pass";
	private static final String MYSQl = "MYSQL";
    private Connection conn;
    
    static void printInfo(String msg){
    	if(PLUGINLOG)
    		fLogger.info(msg);
    	else
    		System.out.println(msg);
    }
    
    static void printDebug(String msg){
    	if(PLUGINLOG)
    		fLogger.info(msg);
    	else
    		System.out.println(msg);
    }
    
    static void printWarn(String msg){
    	if(PLUGINLOG)
    		fLogger.info(msg);
    	else
    		System.out.println(msg);
    }
    
    static void printError(String msg){
    	if(PLUGINLOG)
    		fLogger.error(msg);
    	else
    		System.out.println(msg);
    }
    
    static void printException(Exception e){
    	if(PLUGINLOG)
    		fLogger.error("",e);
    	else
    		e.printStackTrace();
    }
    
    public DBAccess(String DBType,String DBName,String ServerName,String Port,String User,String Password){
    	this.DEBUG = false;
    	this.conn = null;
    	this.conn = makeConnection(DBType,DBName,ServerName,Port,User,Password);
    }

	private Connection makeConnection(String dBType, String dBName,
			String serverName, String port, String user, String password) {
		String db_driver = getJDBCDriver(dBType);
		String URL = getDBURL(dBType,dBName,serverName,port);
		Connection connection = null;
		try {
			Class.forName(db_driver);
			connection = DriverManager.getConnection(URL, user, password);
		} catch (Exception e) {
			printError("Error: makeConnection() | Connect  to database Error!");
			printException(e);
			
			try {
				if ((connection != null) && (!connection.isClosed()))
					connection.close();
			} catch (Exception ex) {
				printException(ex);
			}
			return null;
		}
		return connection;
	}

	
	private String getJDBCDriver(String dbTag) {
		String driver = "";
		if(dbTag.equals("MYSQL"))
			driver = "com.mysql.jdbc.Driver";
		else
			printWarn("db URL: not support this db tag " + dbTag);
		return driver;
	}
	
	
	private String getDBURL(String dbTag, String dbName, String ip,
			String port) {
		String URL ="";
		if(dbTag.equals("MYSQL"))
		  URL = "jdbc:mysql://" + ip + ":" + port + '/' + dbName;
		else
			throw new RuntimeException("不支持的数据库类型:" + dbTag);
		return URL;
	}
	
	public Statement createStatement(){
		Statement stmt = null;
		try {
			stmt = this.conn.createStatement(1004, 1008);
		} catch (Exception e) {
			printException(e);
		}
		  return stmt;
	}
	
	
	public ResultWrapper getResultWrapper(String strSql) throws Exception {
		ResultWrapper result = new ResultWrapper();
		Statement stmt = createStatement();
		ResultSet rs = null;
		try
	    {
	      if (this.DEBUG)
	        printDebug(strSql);
	      rs = stmt.executeQuery(strSql);
	      result.importData(rs);
	    }
	    catch (Exception e)
	    {
	      printException(e);
	      throw e;
	    }

	    try
	    {
	      rs.close();
	    }
	    catch (Exception localException) {
	    }
	    try {
	      stmt.close();
	    }
	    catch (Exception localException1) {
	    }
	    try {
	      rs.close();
	    }
	    catch (Exception localException2) {
	    }
	    try {
	      stmt.close();
	    } catch (Exception localException3) {
	    }
	    return result;
	}
	
	public void close(){
		if (this.conn != null){
			try {
				if (!this.conn.isClosed()) {
					this.conn.close();
					this.conn = null;
					if (this.DEBUG)
						printDebug("dbclose():The DATABASE CONNECT is CLOSED.");
				}
			} catch (Exception e) {
                 printError("dbClose() error!");
                 printException(e);
			}
		}
	}
	
	public static void main(String[] args) {
		DBAccess access = new DBAccess("MYSQL", "epmsgroup", "10.10.12.91", "3308", "system","Hwsystem@com");
	}
}



package utils.db;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ResultWrapper {
		private ArrayList listResult;
		private String[] columnNames;
		private String[] columnRealNames;
		private int[] columnTypes;
		
		ResultWrapper(){
		   this.listResult = null;
		   this.columnNames = null;
		   this.columnRealNames = null;
		   this.columnTypes = null;
		   this.listResult = new ArrayList();
		}
		
		private int getColumnIndex(String columnName){
			for(int i = 1;i<this.columnNames.length;i++){
				 if (this.columnNames[(i - 1)].equalsIgnoreCase(columnName))
				        return i;
			}
			return -1;
		}
		
		public ArrayList<ResultWrapper> getListResult(){
			return this.listResult;
		}
		
		public String getString(int rowIndex, int columnIndex){
			Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    Object str = row[(columnIndex - 1)];
		    if (str != null) {
		      return str.toString();
		    }
		    return null;
		}
		
		public String getString (int rowIndex, String columnName){
			return getString(rowIndex, getColumnIndex(columnName));
		}
		
		public Date getDate(int rowIndex, int columnIndex){
			Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    return (Date)row[(columnIndex - 1)];
		}
		
		public Date getDate(int rowIndex, String columnName)
		  {
		    return getDate(rowIndex, getColumnIndex(columnName));
		  }
		
		public BigDecimal getBigDecimal(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? null : new BigDecimal(str);
		  }

		  public BigDecimal getBigDecimal(int rowIndex, String columnName)
		  {
		    return getBigDecimal(rowIndex, getColumnIndex(columnName));
		  }
		  
		  public boolean getBoolean(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? false : Boolean.valueOf(str).booleanValue();
		  }

		  public boolean getBoolean(int rowIndex, String columnName)
		  {
		    return getBoolean(rowIndex, getColumnIndex(columnName));
		  }

		  public double getDouble(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? 0.0D : Double.parseDouble(str);
		  }

		  public double getDouble(int rowIndex, String columnName)
		  {
		    return getDouble(rowIndex, getColumnIndex(columnName));
		  }

		  public float getFloat(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? 0.0F : Float.parseFloat(str);
		  }

		  public float getFloat(int rowIndex, String columnName)
		  {
		    return getFloat(rowIndex, getColumnIndex(columnName));
		  }

		  public int getInt(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? 0 : Integer.parseInt(str);
		  }

		  public int getInt(int rowIndex, String columnName)
		  {
		    return getInt(rowIndex, getColumnIndex(columnName));
		  }
		  
		  public long getLong(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? 0L : Long.parseLong(str);
		  }

		  public long getLong(int rowIndex, String columnName)
		  {
		    return getLong(rowIndex, getColumnIndex(columnName));
		  }

		  public short getShort(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    String str = row[(columnIndex - 1)].toString();
		    return str == null ? 0 : Short.parseShort(str);
		  }

		  public short getShort(int rowIndex, String columnName)
		  {
		    return getShort(rowIndex, getColumnIndex(columnName));
		  }

		  public Object getObject(int rowIndex, int columnIndex)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    Object str = row[(columnIndex - 1)];
		    return str;
		  }

		  public Object getObject(int rowIndex, String columnName)
		  {
		    return getObject(rowIndex, getColumnIndex(columnName));
		  }
          
		  public List getString(int columnIndex)
		  {
		    String[] aReturn = new String[this.listResult.size()];
		    Object[] row = (Object[])null;
		    for (int i = 0; i < this.listResult.size(); i++)
		    {
		      row = (Object[])this.listResult.get(i);
		      aReturn[i] = row[(columnIndex - 1)].toString();
		    }

		    return Arrays.asList(aReturn);
		  }

		  public List getString(String columnName)
		  {
		    return getString(getColumnIndex(columnName));
		  }

		  public int getRowCount()
		  {
		    return this.listResult.size();
		  }

		  public int getColumnCount()
		  {
		    return this.columnNames.length;
		  }

		  public List getColumnNames()
		  {
		    return Arrays.asList(this.columnNames);
		  }

		  public List getColumnRealNames()
		  {
		    return Arrays.asList(this.columnRealNames);
		  }
		  
		  public int getRowNo(int columnIndex, String columnValue)
		  {
		    Object[] row = (Object[])null;
		    for (int i = 0; i < this.listResult.size(); i++)
		    {
		      row = (Object[])this.listResult.get(i);
		      if (row[(columnIndex - 1)].toString().equals(columnValue)) {
		        return i + 1;
		      }
		    }
		    return -1;
		  }

		  public int getRowNo(String columnName, String columnValue)
		  {
		    return getRowNo(getColumnIndex(columnName), columnValue);
		  }
		  
		  public boolean isEmpty()
		  {
		    return getRowCount() <= 0;
		  }

		  public void setString(int rowIndex, int columnIndex, String value)
		  {
		    Object[] row = (Object[])this.listResult.get(rowIndex - 1);
		    row[(columnIndex - 1)] = value;
		  }

		  public void setString(int rowIndex, String columnName, String value)
		  {
		    setString(rowIndex, getColumnIndex(columnName), value);
		  }
		  
		  public String toString()
		  {
		    if ((this.columnNames == null) || (this.columnNames.length == 0) || (getRowCount() == 0))
		      return "无查询结果";
		    StringBuffer stringBuffer = new StringBuffer();
		    Object[] row = (Object[])null;
		    for (int i = 0; i < this.columnNames.length; i++) {
		      stringBuffer.append(this.columnNames[i] + "|");
		    }
		    stringBuffer.append("\n-------------------------------------------\n");
		    for (int i = 0; i < this.listResult.size(); i++)
		    {
		      row = (Object[])this.listResult.get(i);
		      for (int j = 0; j < row.length; j++) {
		        stringBuffer.append(row[j] != null ? row[j].toString() + "," : "null");
		      }
		      stringBuffer.append("\n");
		    }

		    return stringBuffer.toString();
		  }
		  
		  int importData(ResultSet rs) throws SQLException
		  {
		    int intCount = 0;
		    ResultSetMetaData rsmd = rs.getMetaData();
		    int iColCount = rsmd.getColumnCount();
		    this.columnNames = new String[iColCount];
		    this.columnRealNames = new String[iColCount];
		    this.columnTypes = new int[iColCount];
		    for (int i = 1; i <= iColCount; i++)
		    {
		      this.columnNames[(i - 1)] = rsmd.getColumnLabel(i);
		      this.columnRealNames[(i - 1)] = rsmd.getColumnName(i);
		      this.columnTypes[(i - 1)] = rsmd.getColumnType(i);
		    }

		    Object strTmp = null;
		    Object[] row = (Object[])null;
		    while (rs.next())
		    {
		      row = new Object[iColCount];
		      for (int i = 1; i <= iColCount; i++)
		      {
		        switch (this.columnTypes[(i - 1)])
		        {
		        case 91:
		          strTmp = rs.getTimestamp(i);
		          break;
		        default:
		          strTmp = rs.getString(i);
		        }

		        row[(i - 1)] = strTmp;
		      }

		      this.listResult.add(row);
		      intCount++;
		    }

		    if (intCount == 0) {
		      return 0;
		    }
		    return intCount;
		  }

}



package utils.db;

public class SQLWrapper {
    public static ResultWrapper getResult(String DBType, String DBName, String ServerName, String Port, String User, String Password, String sql){
    	DBAccess mDB = new DBAccess(DBType, DBName, ServerName, Port, User, Password);
    	ResultWrapper rw = null;
    	try
        {
          rw = mDB.getResultWrapper(sql);
        }
        catch (Exception exception)
        {
          mDB.close();
        } 
    	mDB.close();
        return rw;
    }
}



#log4j.rootCategory=debug, console, R
log4j.rootCategory=info,R
#console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss,SSS} %l %p]%m%n

#file
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.Append=false
log4j.appender.R.File=./log/testcase.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}]%m%n

猜你喜欢

转载自hello------world.iteye.com/blog/2302718