Blame view

src/com/sitech/ismp/coll/SQLTarget.java 8.6 KB
1 2
package com.sitech.ismp.coll;
3 4
import org.apache.log4j.Logger;
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class SQLTarget extends CollBase {
	Logger logger = Logger.getLogger(SQLTarget.class);
	String ObjectIP = null;

	String DBType = "ORACLE";
//	String Drivers = "oracle.jdbc.driver.OracleDriver";
	String Drivers = "oracle.jdbc.OracleDriver";
	String driverpre = "jdbc:oracle:thin:@";
	String ObjectIPPort = "1521";
	String SIDName = null;
	String user = null;
	String passwd = null;
	String cUrl = null;

	boolean state = false;
    private Connection dbConnection = null;

    public static Map<String, Connection> connectionsMap = new HashMap<String, Connection>();

    public SQLTarget() {
		
	}

	public SQLTarget(String IP, String cUser, String cPasswd) {
		init(IP, "1521", cUser, cPasswd);
	}

	public SQLTarget(String IP, int cPort, String cUser, String cPasswd) {
		init(IP, String.valueOf(cPort), cUser, cPasswd);
	}

	public SQLTarget(String IP, String cPort, String cUser, String cPasswd) {
		init(IP, cPort, cUser, cPasswd);
	}
	
	public SQLTarget(String IP,String cPort,String sid, String cUser, String cPasswd) {
		init(IP, cPort, sid, cUser, cPasswd);
	}

	public void init(String IP) {
		this.ObjectIP = IP;
		setDBIP(IP);
	}

	public void init(String IP, String cSID, String cUser, String cPasswd) {
		KPISet.clear();
		setDBIP(IP);
		// setPort(cPort );
		setSIDName(cSID);
		setUser(cUser);
		setPasswd(cPasswd);
	}

	public void init(String IP, String cPort, String cSID, String cUser,
			String cPasswd) {
		KPISet.clear();
		setDBIP(IP);
		setPort(cPort);
		setSIDName(cSID);
		setUser(cUser);
		setPasswd(cPasswd);
	}

	public void init(String cUrl, String cUser, String cPasswd) {
		KPISet.clear();
		setUrl(cUrl);
		setUser(cUser);
		setPasswd(cPasswd);
	}

    public void initWithClassname(String dbType, String className, String dburl, String dbuser, String passwd) {
        setDBType(dbType);
        setDrivers(className);
        setUrl(dburl);
        setUser(dbuser);
        setPasswd(passwd);
    }

	/*
	 * public void init(String IP,String cSID,String cUser, String cPasswd){
	 * this.ObjectIP = IP; setDBIP(IP ); setSIDName(cSID); setUser(cUser);
	 * setPasswd(cPasswd); }
	 */

    public void setDBType(String DBType) {
        this.DBType = DBType;
    }

    public void setDBIP(String ObjectIP) {
		this.ObjectIP = ObjectIP;
	}

	public void setDrivers(String Drivers) {
		this.Drivers = Drivers;
	}

	public void setPort(String cPort) {
		this.ObjectIPPort = cPort;
	}

	public void setSIDName(String cSIDName) {
		this.SIDName = cSIDName;
	}

	public void setUser(String cUser) {
		this.user = cUser;
	}

	public void setPasswd(String cPasswd) {
		this.passwd = cPasswd;
	}

	public void setUrl(String cUrl) {
		this.cUrl = cUrl;
	}


	/**
	 * 获得数据库连接
	 * @return
	 */
	public Connection getConnection() {
		String url = null;
		if (cUrl == null) {
			url = this.driverpre + ObjectIP + ":" + ObjectIPPort + ":" + SIDName;
		} else {
			url = cUrl;
		}

        dbConnection = connectionsMap.get(ObjectIP + "_" + user);
        if (dbConnection == null) {
            try {
//                if (dbConnection == null || dbConnection.isClosed()) {
                logger.info("-- create new " + DBType + " Connection,Url=" + url);
                Class.forName(Drivers);
                dbConnection = DriverManager.getConnection(url, user, passwd);
                logger.info("-- create new " + DBType + " Connection Success!!!");
//                }
                state = true;
                connectionsMap.put(ObjectIP + "_" + user, dbConnection);
            } catch (Exception e) {
                state = false;
                logger.info("-- create new " + DBType + " Connection Failed!!! url=" + url + " user=" + user + " passwd=" + passwd, e);
            }
        } else {
//            connectionsMap.remove(ObjectIP + "_" + user);
            try {
                if (dbConnection.isClosed()) {
                    logger.info("-- connection lose effectiveness, recreate new " + DBType + " Connection, DBUrl=" + url);
                    Class.forName(Drivers);
                    dbConnection = DriverManager.getConnection(url, user, passwd);
                    logger.info("-- recreate new " + DBType + " Connection Success!!!");
                }
                connectionsMap.put(ObjectIP + "_" + user, dbConnection);
                state = true;
            } catch (Exception e) {
                state = false;
                logger.info("--recreate new " + DBType + " Connection Failed!!! url=" + url + " user=" + user + " passwd=" + passwd, e);
            }
        }
		return dbConnection;
	}

	public void releaseResources() {
		try {
			if (dbConnection != null && !dbConnection.isClosed()) {
				dbConnection.close();
			}
		} catch (SQLException se) {
			se.printStackTrace();
		}
	}

	public Vector getKPISet(String sql) {
		Vector recordSet = new Vector();
		PreparedStatement pstmt = null;
		ResultSet result = null;
192 193 194
		if (!getState()) {
			return recordSet;
		}
195
196
		try {
197
			pstmt = dbConnection.prepareStatement(sql);
198 199 200 201 202 203 204 205 206 207 208 209 210
		} catch (SQLException e) {
			throw new RuntimeException("Exception while exec sql :" + sql, e);
		}

		boolean hasResult = false;
		try {
			hasResult = pstmt.execute();
		} catch (SQLException e) {
			logger.error("pstmt.execute() has error!",e);
			e.printStackTrace();
		}
		try {
211 212 213 214 215
			if (hasResult) {
				result = pstmt.getResultSet();
				ResultSetMetaData rsmd = result.getMetaData();
				int iColumnCount = rsmd.getColumnCount();
				while (result.next()) {
216
					Vector vTemp = new Vector();
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
					for (int i = 0; i < iColumnCount; i++) {
						Object oTemp = result.getObject(i + 1);
						String sTemp = oTemp == null ? "" : oTemp.toString();
						vTemp.addElement(sTemp.trim());
					}
					recordSet.add(vTemp);
				}
                result.close();
			}
			pstmt.close();
		} catch (Exception e) {
			throw new RuntimeException("Exception while exec sql :" + sql, e);
		} finally {
				try {
					if(pstmt!=null){
						pstmt.close();
					}
					if(result!=null){
						result.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}

		}
		return recordSet;
	}

	public boolean getState() {
		getConnection();
		try {
			if (!state) {
249
                Thread.sleep(5000);// 间隔5s重试第二次连接
250 251 252
				System.err.println("--second--conn error----");
				getConnection();
				if (!state) {
253
					Thread.sleep(5000);// 再间隔5s重试第三次连接
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
                    System.err.println("--third--conn error----");
                    getConnection();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		    releaseResources();
		}
		return state;
	}

	public String getSQLKPISetInfo(String sql) {
		if (sql == null || sql.equals(""))
			return "";
		Vector result = getKPISet(sql);
		String sTable = "";
		for (int i = 0; i < result.size(); i++) {
			Vector row = (Vector) result.elementAt(i);
			String sRow = "";
			for (int j = 0; j < row.size(); j++) {
				sRow = sRow + "," + row.elementAt(j);
			}
			sTable = sTable + "\n" + sRow;
		}
		return sTable;
	}

	public Vector getSQLKPISet(String sql) {
		return getSQLKPISet(sql, 0);
	}

	public Vector getSQLKPISet(String sql, int iPos) {
		if (sql == null || sql.equals(""))
			return null;
		Vector result = getKPISet(sql);
		Vector tmp_result = new Vector();
		for (int i = 0; i < result.size(); i++) {
			Vector record = (Vector) result.elementAt(i);
			String kpiinfo = (String) record.elementAt(iPos);
			tmp_result.add(kpiinfo);
		}
		return tmp_result;
	}

	public Vector getColumn(Vector recordSet, int col) {
		Vector ret = new Vector();

		for (int i = 0; i < recordSet.size(); i++) {
			ret.add(((Vector) recordSet.elementAt(i)).elementAt(col));
		}
		return ret;
	}

	public Vector getSQLKPIResult(String sql) {
		if (sql == null || sql.equals("")){
			return null;
        }
		
		long beginTime = System.currentTimeMillis();

		Vector result =  getKPISet(sql);
		
		long used = System.currentTimeMillis() - beginTime;
		logger.info("-- used " + used + "/1000 seconds," + sql);

		return result;
	}

	public String getSQLKPIInfo(String sql) {
		if (sql == null || sql.equals(""))
			return "";
		String kpiinfo = "";
		Vector result = getKPISet(sql);

		if (result.size() > 0) {
			Vector record = (Vector) result.elementAt(0);
			kpiinfo = (String) record.elementAt(0);
		}
		System.out.println("kpiinfo=" + kpiinfo);
		return kpiinfo;
	}
336 337 338
	/**
	 * 释放数据库连接
	 */
339
	public void release() {
340
		releaseResources();
341 342 343
	}

}