MyException - 我的异常网
当前位置:我的异常网» 编程 » 线程示范

线程示范

www.MyException.Cn  网友分享于:2013-02-18  浏览:2次
线程示例
package com.poson.aspz;

import java.io.File;
import java.rmi.RemoteException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import com.poson.aspz.db.TranContext;
import com.poson.aspz.util.Config;
import com.poson.aspz.util.Const;
import com.poson.aspz.util.MyLoger;
import com.poson.aspz.util.Util;
import java.net.MalformedURLException;
import ws.clinet.axis2.WebSoapBindingImplServiceCallbackHandler;
import ws.clinet.axis2.WebSoapBindingImplServiceStub;
import java.sql.Connection;
import java.sql.DriverManager;

public class OnTimeCreditIntf  extends Thread
{
	private boolean bSuperUser = false;
	private boolean working = false;
	private String planXMLFileFN = "";
	private String path = "";
	private String staffNo = "";
	private String pswd = "";
	private String staffId = "";
	private String siteId = "";
	private String areaId = "";
	private TranContext myDBTrans = null;
	private String curCreatePZDate = "";
	protected Connection conn;
	
	//private static Log log = LogFactory.getLog(Worker.class);
	//private static MyLoger log = new MyLoger();
	private Logger logger = Logger.getLogger(OnTimeCreditIntf.class);
	public OnTimeCreditIntf() 
	{
	
	}

	public Connection getConnection() {
		try {
			conn = DriverManager.getConnection(Const.CONFIG_XML_DB_URL);
			return conn;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 建立连接
	 * @param driver
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 */
	public Connection getConnection(String driver, String url, String user, String password) {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public List getBJOnTimeCreditIntfSumbit() throws SQLException
	{
		ArrayList list = new ArrayList();
		ResultSet rs = null;
		StringBuffer strSql = new StringBuffer();
		strSql.append(" SELECT TRIM(ORDER_SERIAL_NBR) ORDER_SERIAL_NBR, ");
		strSql.append(" TRIM(OWE_BUSINESS_TYPE_ID) OWE_BUSINESS_TYPE_ID,TRIM(STAFF_ID) STAFF_ID, ");
		strSql.append(" TRIM(SERV_ID) SERV_ID,TO_CHAR(CREATED_DATE, 'yyyymmddhhmmss') CREATED_DATE,TO_CHAR(COMPLETED_DATE, 'yyyymmddhhmmss') COMPLETED_DATE, ");
		strSql.append(" TRIM(STATE) STATE,TO_CHAR(STATE_DATE, 'yyyymmddhhmmss') STATE_DATE,TRIM(PROCESS_COUNT) PROCESS_COUNT, ");
		strSql.append(" TRIM(PRE_SERV_STATE) PRE_SERV_STATE,TRIM(REMARK) REMARK,TRIM(CHARGE) CHARGE,TRIM(BALANCE) BALANCE, ");
		strSql.append(" TRIM(CREDIT) CREDIT,TRIM(OWE_TASK_ITEM_ID) OWE_TASK_ITEM_ID ");
		strSql.append(" FROM A_WORK_ORDER ");
		strSql.append(" WHERE STATE='P0C' AND ROWNUM<500 ORDER BY ORDER_SERIAL_NBR ");
		rs = myDBTrans.executeQuery(strSql.toString());
		while (rs.next()) 
		{
        	HashMap planInfo = new HashMap();
        	planInfo.put("ORDER_SERIAL_NBR",rs.getString("ORDER_SERIAL_NBR"));	
        	planInfo.put("OWE_BUSINESS_TYPE_ID",rs.getString("OWE_BUSINESS_TYPE_ID"));
        	planInfo.put("STAFF_ID",rs.getString("STAFF_ID"));	
        	planInfo.put("SERV_ID",rs.getString("SERV_ID"));
        	planInfo.put("CREATED_DATE",rs.getString("CREATED_DATE"));	
        	planInfo.put("COMPLETED_DATE",rs.getString("COMPLETED_DATE"));	
        	planInfo.put("STATE",rs.getString("STATE"));	
        	planInfo.put("STATE_DATE",rs.getString("STATE_DATE"));	
        	planInfo.put("PROCESS_COUNT",rs.getString("PROCESS_COUNT"));	
        	planInfo.put("PRE_SERV_STATE",rs.getString("PRE_SERV_STATE"));
        	planInfo.put("REMARK",rs.getString("REMARK"));
        	planInfo.put("CHARGE",rs.getString("CHARGE"));
        	planInfo.put("BALANCE",rs.getString("BALANCE"));
        	planInfo.put("CREDIT",rs.getString("CREDIT"));
        	planInfo.put("OWE_TASK_ITEM_ID",rs.getString("OWE_TASK_ITEM_ID"));
			list.add(planInfo);  
		}
        if (rs != null) {
        	rs.close();
        	rs = null;
          }
		return list;
	}

//	public void updateBJOnTimeCreditIntfPlan(String requestId,String serial) throws SQLException
//	{
//		ResultSet rs = null;
//		StringBuffer strSql = new StringBuffer();
//		strSql.append(" UPDATE A_WORK_ORDER SET STATE='P0P',REMARK='处理成功',SERIAL='" + serial + "'");
//		strSql.append(" WHERE ORDER_SERIAL_NBR= " + requestId);
//		rs = myDBTrans.executeQuery(strSql.toString());
//	}

	public void deleteBJOnTimeCreditIntfPlan(String requestId) throws SQLException
	{
		StringBuffer strSql = new StringBuffer();
		strSql.append(" DELETE FROM A_WORK_ORDER ");
		strSql.append(" WHERE ORDER_SERIAL_NBR= " + requestId);
		myDBTrans.doBatch(strSql.toString());
	}
	
	public void  insertBJOnTimeAWorkOrderLog(String requestId,String serial) throws SQLException
	{
		StringBuffer strSql = new StringBuffer();
		strSql.append(" INSERT INTO A_WORK_ORDER_LOG (order_serial_nbr,owe_business_type_id,staff_id, ");
		strSql.append(" serv_id,created_date,completed_date,state,state_date,process_count,pre_serv_state,remark,");
		strSql.append(" tran_manual_date,hd_staff_id,charge,balance,credit,owe_task_item_id,SERIAL) ");
		strSql.append(" select order_serial_nbr,owe_business_type_id,staff_id, " );
		strSql.append(" serv_id,created_date,completed_date,'P0P',sysdate,process_count,pre_serv_state,remark,");
		strSql.append(" null,null,charge,balance,credit,owe_task_item_id,'" +serial + "' from A_WORK_ORDER ");
		strSql.append(" WHERE ORDER_SERIAL_NBR= " + requestId);
		myDBTrans.doBatch(strSql.toString());
	}
	
	public void updateBJOnTimeCreditFailPlan(String requestId,String error, String serial) throws SQLException
	{
		StringBuffer strSql = new StringBuffer();
		strSql.append(" UPDATE A_WORK_ORDER SET STATE='P0E',state_date=sysdate,REMARK='" + error + "',SERIAL='" + serial + "'");
		strSql.append(" WHERE ORDER_SERIAL_NBR= " + requestId);
		myDBTrans.doBatch(strSql.toString());
	}
	
	public OnTimeCreditIntf(String staffNo, String pswd, String path, String planXMLFileFN){
//		if(this.conn == null) {
//			this.conn = this.getConnection();
//			this.conn.setAutoCommit(true);
//		}	
		
		this.staffNo = staffNo;
		this.pswd = pswd;
		this.path = path;
		this.planXMLFileFN = path + File.separator + planXMLFileFN;
		
		// 启动数据库连接
		myDBTrans = new TranContext();
	}
	

	public boolean isWorking() {
		return working;
	}
	
	public void setWorking(boolean working) {
		this.working = working;	
	}
	
	public void run()
	{	
		// 开始无限循环工作
		long times = 0;
		int sleepTime = 60; 
		while (working)
		{
		  try 
		  {
			 List curSubmitReport = getBJOnTimeCreditIntfSumbit();			
			 String xmlFileName = Util.getAppTopFolderPath() + Const.CONFIG_XML_FILE_NAME;
	         Config config = new Config(xmlFileName);
	         sleepTime = config.sleep;
			 for (int n = 0; n < curSubmitReport.size(); n++)
			 {
				try 
				{
				   Date curDate = new Date();						
				   HashMap planInfo = (HashMap) curSubmitReport.get(n);
				   String requestId = (String) planInfo.get("ORDER_SERIAL_NBR");
				   String servId = (String) planInfo.get("SERV_ID");
				   String synType = (String) planInfo.get("OWE_BUSINESS_TYPE_ID");
				   String stateTime = (String) planInfo.get("STATE_DATE");
				   String curBalance = (String) planInfo.get("BALANCE");
				   String creditValue = (String) planInfo.get("CREDIT");
				   String random = String.valueOf(Math.random()).substring(2,10);
			       Date currentTime=new Date();
			       SimpleDateFormat formatter=new SimpleDateFormat("yyyyMMddHHmmss");
			       String time=formatter.format(currentTime);
			       String serial = time + random + "10" + "02";

			       WebSoapBindingImplServiceStub.OnTimeCreditControlReq onTimeCreditControlReq = new WebSoapBindingImplServiceStub.OnTimeCreditControlReq();
			       WebSoapBindingImplServiceStub.OnTimeCreditControl onTimeCreditControl = new WebSoapBindingImplServiceStub.OnTimeCreditControl();
			       onTimeCreditControlReq.setRequestId(serial);
			       onTimeCreditControlReq.setServId(servId);
			       onTimeCreditControlReq.setStateTime(stateTime);
			       onTimeCreditControlReq.setSynType(Integer.parseInt(synType));
			       onTimeCreditControlReq.setInterfaceId("");
			       onTimeCreditControlReq.setCurBalance(curBalance);
			       onTimeCreditControlReq.setCreditValue(creditValue);
			       onTimeCreditControl.setIn0(onTimeCreditControlReq);

				   logger.info("**OnTimeCreditControl**请求参数如下:"
			                    + "\n RequestId(请求流水): " + onTimeCreditControlReq.getRequestId()
			                    + "\n ServId(用户标识): " + onTimeCreditControlReq.getServId()
			                    + "\n SynType(同步类型): " + onTimeCreditControlReq.getSynType()
			                    + "\n curBalance(实时结余): " + onTimeCreditControlReq.getCurBalance()
			                    + "\n creditValue(用户信用度): " + onTimeCreditControlReq.getCreditValue()
			                    + "\n StateTime(状态时间): " + onTimeCreditControlReq.getStateTime());

				   String result = callOnTimeCreditIntfWebServices(onTimeCreditControl,config);
				   
				   if("0".equals(result))
				   {
					   insertBJOnTimeAWorkOrderLog(requestId,serial);
					   deleteBJOnTimeCreditIntfPlan(requestId);
					   logger.info("=========OnTimeCreditControl successful,servId:"+servId+"=========");
				   }
				   else
				   {
					  myDBTrans.roolback();
					  updateBJOnTimeCreditFailPlan(requestId,result,serial);
					  logger.info("=========OnTimeCreditControl failure,servId:"+servId+"当前流水执行失败!!!" );
				   }						   
				   myDBTrans.commit();
				   
					// 关闭数据集
					try 
					{
						myDBTrans.close();
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
					}
				 }
				 catch (RuntimeException e)
				 {
				   logger.info("=========failure=========当前条目计划执行失败!!!" );
				   e.printStackTrace();
				   myDBTrans.roolback();
				   myDBTrans.close();
				 }					
			 }				 
		  }
          catch(Exception ex)
          {
			ex.printStackTrace();
			Util.outPutInfo("未知错误发生" + ex.getMessage());
		  }

			// 关闭数据集
			try 
			{
				myDBTrans.close();
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
		  // 睡眠一段时间后再工作
		  try 
		  {
			sleep(sleepTime);
			myDBTrans.freeCon();
			myDBTrans.initConnection();
		  } 
		  catch(InterruptedException e)
		  {
			Util.outPutInfo("线程睡眠被打断,程序继续执行: " + e.getMessage());
			e.printStackTrace();
		  }		  
		}
	}	
		
private String callOnTimeCreditIntfWebServices(WebSoapBindingImplServiceStub.OnTimeCreditControl onTimeCreditControlReq,Config config)
{
   try 
   {           	
	 WebSoapBindingImplServiceStub  stub = new WebSoapBindingImplServiceStub(config.wsEndpoint);
	 WebSoapBindingImplServiceStub.OnTimeCreditControlResponse onTimeCreditControlResp = stub.onTimeCreditControl(onTimeCreditControlReq);
	 logger.info("result is: \n"+onTimeCreditControlResp.getOnTimeCreditControlReturn().getResult());
	 String result = onTimeCreditControlResp.getOnTimeCreditControlReturn().getResult();
	 if("0".equals(result)) return "0";
	 else return onTimeCreditControlResp.getOnTimeCreditControlReturn().getErrorMessage();
   } 
   catch(Exception e)
   {
	 e.printStackTrace();
	 return "5000";
   } 
}


public static void main(String[] args)
{
  String path = Util.getAppTopFolderPath();
  String user = "jlz";
  String pswd = "1q2w3e4r";		
		
  Thread thread = new OnTimeCreditIntf(user, pswd, path, Const.SUBMIT_PLAN_XML_FILE_NAME);
  thread.setDaemon(false);
  ((OnTimeCreditIntf) thread).setWorking(true);
  thread.start();

  // 主线程进入无限睡眠状态,其创建的子线程 thread 继续工作
  try
  {
	Thread.sleep(Long.MAX_VALUE);
  } 
  catch(InterruptedException e) 
  {
	System.out.println("主线睡眠状态被打断,程序继续执行...\n" + e.getMessage());
  }

  // 当主线程睡眠被打断时,程序结束,并设置子线程状态,让其在完成必要工作后也结束
  ((OnTimeCreditIntf) thread).setWorking(false);
}
	
}

 

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有