⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbfunctionsmanager.java

📁 this is example use EJB with jboss.
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/* * Copyright(C) 2008, NTT AT Co., Ltd. * Project: AWGStar * * Notes: *  N/A * * Record of change: * Date          Version      	Name       		Content * 2008/12/20    1.0            <TuanNA>      	First create       */package jp.co.ntt.awgview.server.dao;import java.io.File;import java.io.Serializable;import java.sql.ResultSet;import java.sql.SQLException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;import jp.co.ntt.awgview.server.common.CsvWriter;import jp.co.ntt.awgview.server.common.LogWriter;import jp.co.ntt.awgview.server.common.Setting;import jp.co.ntt.awgview.server.common.Utils;import jp.co.ntt.awgview.server.constant.AWGNEConstants;import jp.co.ntt.awgview.server.constant.AlarmLevelConstants;import jp.co.ntt.awgview.server.constant.Constants;import jp.co.ntt.awgview.server.constant.DBConstants;import jp.co.ntt.awgview.server.dao.ConnectionPool;import jp.co.ntt.awgview.server.dao.ConnectionPoolFactory;import jp.co.ntt.awgview.server.dao.DBConnection;import jp.co.ntt.awgview.server.vo.BlockVO;import jp.co.ntt.awgview.server.vo.ConnectorVO;import jp.co.ntt.awgview.server.vo.NodeHelper;import jp.co.ntt.awgview.server.vo.NodeVO;import jp.co.ntt.awgview.server.vo.OperationVO;import jp.co.ntt.awgview.server.vo.PackageTypeVO;import jp.co.ntt.awgview.server.vo.PackageVO;import jp.co.ntt.awgview.server.vo.PortVO;import jp.co.ntt.awgview.server.vo.TrapVO;import jp.co.ntt.awgview.server.vo.UserVO;import jp.co.ntt.awgview.server.vo.ConnectorVO.PPConnection;import jp.co.ntt.awgview.server.vo.ConnectorVO.PackageConnection;/** * Class name : DBFunctionsManager <BR> *  * Package : jp.co.nttat.awgstar.server.dao <BR> *   * Description: This class provide methods necessary in order to communicate * with the database. Also, manage users and distribute resources<BR> *  * @author : AI&T * @version : 1.0 */public class DBFunctionsManager implements Serializable {	private static final long serialVersionUID = -4622298009028780481L;	// Declare public variables for all users	//	private static ConnectionPool conPool = null;	private static Hashtable<String, Integer> htblQueueNameRes; /*Contains queue name consists of	 															 request channel and response channel*/	private static boolean isTimerRunning         = false;	//private static boolean isJBossDetecterStarted = false;	private static boolean isLoadedAlarmType      = false;	private static boolean isServerStarted        = false;	private static Hashtable<String, UserVO> hashUserOnline;	private static int userTimeout = 60; /* time prior check timeout of all client (unit in second)*/		/* This is time ratio between time keep alive (on client) and check client	 * timed out on server. The time which client send alive sign to server should be smaller than at	 * least 1/2 time prior check client of server.	 */	private static int  tmRatioKeepAlive = 2;	public  static long lastTime = 0;	private static Vector<UserVO> vtUserOnline = null;		public static final String FS = java.io.File.separator; /*Define separate directory symbol*/	public static String alarmCsvFile     = null; /*The path of trap backup file*/	public static String operationCsvFile = null; /*The path of operation log backup file*/	public static int maxBackupCsvFile    = 5;    /*Maximum of file CSV for trap/operation log to backup*/	public static int tmBackupInDays      = 7;    /*Records will backed up which getting from database 													in tmBackupInDays days oldest*/	// Define private variables for each user	private Hashtable<Object, Object> htblPutField = null;	public DBConnection conn = null; /* One object connection received from a connection pool*/	private String userIP = ""; /* The IP address of client (corresponding for each user)*/	private String userName = "Server";	private String alarmTblview     = ""; /* view table for load trap */	private boolean isAlarmTblViewCreated = false;	private String operationTblView  = ""; /* view table for load user log */	private boolean isLogTblViewCreated   = false;	/* Queue name resource distributed for each user */	private String requestQueueName  = null; /* Used for sending the data */	private String responseQueueName = null; /* Used for receiving data */	// Declare variables used for loading trap history and user log	private long countObject         = 0; 	private int  offsetRecord2Recv   = 0; /*Record offset to get data at one position specified*/	private int  lmAmountRecord2Recv = 0; /*Limit the amount of record for each time receiving data*/		//Number of connection created initial, this available if not 	//exceeded maximum of connection	private static int initNumOfConnection = 100;	private static boolean bwaitIfBusy = false;	/**	 * Constructor	 */	public DBFunctionsManager() {		try {			// result = new JResult();			//Initialize variables			htblPutField = new Hashtable<Object, Object>();			if (htblQueueNameRes == null){				htblQueueNameRes = new Hashtable<String, Integer>();				LogWriter.getDBLogger().info("Create new <htblQueueNameRes>...OK!");			}			if (hashUserOnline == null){				hashUserOnline = new Hashtable<String, UserVO>();				LogWriter.getDBLogger().info("Create new <hashUserOnline>...OK!");			}			if (!isServerStarted){				/* Read configuration file */				Setting.readConfig();				//Get parameters setting and initialize database connection				initDB(initNumOfConnection, false);				//Load queue resource for each client				loadQueueNameRes();								//Set path for log file				if (operationCsvFile == null) {					operationCsvFile = Utils.genPathDirectory(true, Setting.getJBossHome()										, "server", "default", "log", "awgview", "operation", "operationLog");				}				if (alarmCsvFile == null) {					alarmCsvFile = Utils.genPathDirectory(true, Setting.getJBossHome()										, "server", "default", "log", "awgview", "alarm", "alarmLog");				}				LogWriter.getDBLogger().info("Initializing server...OK!");				isServerStarted = true;			}			/*			 * Create one thread to check user timed out. This is needed to			 * release some resources used by user in the case such as network			 * break down. 			 */			runThread();					} catch (Exception e) {			isServerStarted = false;			LogWriter.getDBLogger().error(					"Error occurred while initializing DBFunctionsManager object.");		}	}		/**	 * Constructor	 * @param initialConnection	 * 			Initial number of connection to the database	 * @param waitIfBusy	 * 				Set true to wait if no connection available, otherwise false	 */	public DBFunctionsManager(int initialConnection, boolean waitIfBusy) {		initNumOfConnection = initialConnection;		bwaitIfBusy = waitIfBusy;		htblPutField = new Hashtable<Object, Object>();		if (!isServerStarted){			/* Read configuration file */			Setting.readConfig();			initDB(initNumOfConnection, waitIfBusy);			//Set path for log file			if (operationCsvFile == null) {				operationCsvFile = Utils.genPathDirectory(true, Setting.getJBossHome()									, "server", "default", "log", "awgview", "operation", "operationLog");			}			if (alarmCsvFile == null) {				alarmCsvFile = Utils.genPathDirectory(true, Setting.getJBossHome()									, "server", "default", "log", "awgview", "alarm", "alarmLog");			}			isServerStarted = true;					}	}	/**	 * Read all parameters necessary to start server, then create one connection	 * pool.	 * 	 * @return true if complete success.	 */	private boolean initDB(int initConnection, boolean waitIfBusy) {				long start = System.currentTimeMillis();		try {			// Create a connection pool that used for overall connections from			// client to the database.			conPool = ConnectionPoolFactory.getConnectionPool();			conPool.initInstance(Setting.getDBName(), Setting.getDBHost(),					Setting.getDBPort(), Setting.getDBUserName(), Setting.getDBUserPass(), initConnection, waitIfBusy);			return true;		} catch (Exception e) {			LogWriter.getDBLogger().error(e.toString());		}		LogWriter.getDBLogger().info("Time:" + (System.currentTimeMillis() - start));		return false;	}	/**	 * Receive a connection to the database	 * 	 * @return JResult object. Check method isSucceeded() of this is true for	 *         success, otherwise false.	 * @throws Exception	 */	public JResult open(){		JResult result = new JResult();		try {			// Get a available connection			if (!conPool.isConnected()){				if (!initDB(initNumOfConnection, bwaitIfBusy)) {					throw new SQLException("Create connection pool failed. " +							"Check for make sure the database server is already started.");				}			} 			conn = conPool.getConnection();			if (conn != null) {				//When the database server stopped, the conn object can not null				//because it is received from vector object which contains connection pooled before.				//So check the connection is necessary				if (!checkConnection(conn)){					throw new SQLException("Cannot connect to server. " +							"Check for make sure the database server is already started.");				}				LogWriter.getDBLogger().info("Opening connection... OK!");				result.returnCode(JResult.DBOPR_SUCCESS);				return result;			} else {				result.setMessage("Cannot receive connection from pool. " +						"This ocurrs maybe when number of connection has limit reached.");			}		} catch (SQLException e) {			LogWriter.getDBLogger().error(e.getMessage());			result.setMessage(e.getMessage());		} catch (Exception e) {			e.printStackTrace();			LogWriter.getDBLogger().error(e.getMessage());			result.setMessage(e.getMessage());		}		conn = null;		result.returnCode(JResult.DBOPR_ERROR_CONNECT_DB_FAILED);		return result;	}	/**	 * Free the current connection	 * 	 * @return true if success. Otherwise return false.	 */	public boolean close() {		try {			// free the current connection from connection pool.			if (conn != null) {				conPool.free(conn.getConnection());				conn = null;				LogWriter.getDBLogger().info("Closing connection...OK!");			}			return true;		} catch (Exception e) {			LogWriter.getDBLogger().error("Closing connection...Failed: " + e.getMessage());			return false;		}	}		/**	 * Check database server is working or not. If not, so try to 	 * @param dbConn	 * 				Use dbConn object to sending query to the database	 * @return true if database is working, otherwise false	 */	public boolean checkConnection(DBConnection dbConn){		if (dbConn != null){			try {				//The way simple to check database server is working				dbConn.execQuery("select now()");				LogWriter.getDBLogger().info("Check database...OK!");				return true;			} catch (Exception e) {				LogWriter.getDBLogger().error("Connection to the database server refused!");			}		} 		//Close all connections pooled for re-get connection pool in next time		closeAllConnection();		return false;	}		/**	 * Close all connection pooled	 * @return true if success, otherwise false if error occurs	 */	public static boolean closeAllConnection() {		try {			// free all current connection from connection pool.			LogWriter.getDBLogger().info("Closing all connections " +										"(free and using) from connection pool");			if (conPool != null) {				conPool.closeAllConnections();				LogWriter.getDBLogger().info("--> OK!");			}			return true;		} catch (Exception e) {		}		return false;	}	/**	 * Get timeout value	 * 	 * @return time unit in second	 */	public static int getUserTimeout() {		// Get time prior in minute to check user timed out.		userTimeout = Setting.getKeepAliveTimeOut();		return userTimeout;	}	/**	 * Get time ratio check timed out	 * 	 * @return time ratio check timed out	 */	public static int getTimeRateChkAlive() {		return tmRatioKeepAlive;	}		/**	 * Get private queue name for each user	 * @return Queue name for response channel	 */	public String getUserResponseQueueName() {		return this.responseQueueName;	}		/**	 * Get private queue name for each user	 * @return Queue name for request channel	 */	public String getUserRequestQueueName() {		return this.requestQueueName;	}		/**	 * Get virtual view of operation table	 * @return operation virtual view table	 */	public String getOperationViewTbl() {		return this.operationTblView;	}		/**	 * Get virtual view of trap table	 * @return trap virtual view table	 */	public String getAlarmViewTbl() {		return this.alarmTblview;	}		/**	 * Create one thread to check user timed out. This is needed to release some	 * resources used by user in the case such as network break down.	 */	public static void runThread() {		try{			int timeDelay;			if (!isTimerRunning) {				userTimeout = Setting.getKeepAliveTimeOut();				java.util.Timer timer = new java.util.Timer(true);				Timer userTimer = new Timer();				timeDelay = getUserTimeout() * 1000/tmRatioKeepAlive; //unit in millisecond				timer.schedule(userTimer, 0, timeDelay);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -