Project

General

Profile

1
package eu.dnetlib.data.claimsDemo;
2

    
3
import com.sun.rowset.CachedRowSetImpl;
4
import org.apache.log4j.Logger;
5

    
6
import javax.sql.rowset.CachedRowSet;
7
import java.sql.*;
8
import java.util.ArrayList;
9
import java.util.List;
10

    
11
/**
12
 * @author eri Sql Store class to connect to the DB backend
13
 */
14

    
15
public class SqlStore {
16

    
17
	private Logger log = Logger.getLogger(this.getClass());
18

    
19
	private String dbUrl;
20
	private String dbUser;
21
	private String dbPassword;
22
	private Connection connection;
23

    
24
	private String dbDriver;
25

    
26
	public SqlStore(String dbUrl, String dbUser, String dbPassword, String dbDriver)  {
27
		this.dbDriver = dbDriver;
28
		this.dbUser = dbUser;
29
		this.dbUrl = dbUrl;
30
		this.dbPassword = dbPassword;
31

    
32
	}
33

    
34
	public SqlStore() throws Exception {
35

    
36
	}
37

    
38

    
39
	public void init() throws ClassNotFoundException, SQLException {
40
 			Class.forName(dbDriver);
41
//			this.getConnection();
42

    
43

    
44
	}
45

    
46
	public void destroy() throws SQLException {
47
		this.closeConnection();
48

    
49
	}
50

    
51
	public void close() throws SQLException {
52
		closeConnection();
53

    
54
	}
55

    
56
	/**
57
	 * Establishes a JDBC connection to the database server without a given DB.
58
	 * Used in order to create or drop databases.
59
	 *
60
	 * @throws SQLException
61
	 */
62
	public void getConnectionNoDatabase() throws SQLException {
63
		String parsedUrl = this.parseUrl(dbUrl);
64
		log.info("Connecting to " + parsedUrl + dbUser );
65
		connection = (Connection) DriverManager.getConnection(parsedUrl, dbUser, dbPassword);
66
		log.info("Connected to " + parsedUrl);
67

    
68
	}
69

    
70
	/**
71
	 * Establishes a connection to a given DB.
72
	 *
73
	 * @throws SQLException
74
	 */
75
	public void getConnection() throws SQLException {
76

    
77
			log.info("Attempting connection to : " + this.dbUrl + " for " + this.dbUser );
78
			connection = (Connection) DriverManager.getConnection(this.dbUrl, dbUser, dbPassword);
79
			log.info("Connected to " + this.dbUrl);
80

    
81
	}
82

    
83
	/**
84
	 * Closes Database Statement.
85
	 *
86
	 * @throws SQLException
87
	 */
88
	public void closeStatement(Statement st) throws SQLException {
89
		log.debug("Closing Statement...");
90
		if (st != null) {
91
			st.close();
92
		}
93

    
94
	}
95

    
96
	/**
97
	 * Closes Database Resultset.
98
	 *
99
	 * @throws SQLException
100
	 */
101
	public void closeResultset(ResultSet rs) throws SQLException {
102
		log.debug("Closing Resultset...");
103
		if (rs != null) {
104
			rs.close();
105
		}
106

    
107
	}
108

    
109
	/**
110
	 * Closes Database connections.
111
	 *
112
	 * @throws SQLException
113
	 */
114
	public void closeConnection() throws SQLException {
115
		log.debug("Closing Connection...");
116
		if (connection != null) {
117
			connection.close();
118
		}
119

    
120
	}
121

    
122
	/**
123
	 * Executes the @param command stored procedure in the Database. Stored
124
	 * procedure parameters are specified in values.
125
	 *
126
	 * @param command
127
	 * @param values
128
	 * @return
129
	 * @throws SQLException
130
	 */
131
	public ResultSet executeStoredProcedure(String command, ArrayList<String> values) throws SQLException {
132
		java.sql.CallableStatement callableStatement = null;
133
		log.debug("  Executing   Query ..." + command);
134

    
135
			callableStatement = this.connection.prepareCall(command);
136
			int pos = 1;
137

    
138
			for (String v : values) {
139

    
140
				callableStatement.setObject(pos, v);
141

    
142
				pos++;
143
			}
144

    
145
			callableStatement.execute();
146
			return callableStatement.getResultSet();
147

    
148

    
149

    
150
	}
151

    
152
	/**
153
	 * Executes the stored query procedure specified by @param command.
154
	 *
155
	 * @param command
156
	 * @return
157
	 * @throws SQLException
158
	 */
159
	public ResultSet executeStoredProcedure(String command) throws SQLException {
160
		log.debug("  Executing   Query ..." + command);
161
		java.sql.CallableStatement callableStatement = null;
162

    
163
			callableStatement = this.connection.prepareCall(command);
164

    
165
			callableStatement.execute();
166
			return callableStatement.getResultSet();
167

    
168

    
169

    
170
	}
171

    
172
	/**
173
	 * Executes the @param query
174
	 *
175
	 * @param command
176
	 * @return
177
	 * @throws SQLException
178
	 */
179
	public ResultSet executeQuery(String command) throws SQLException, SQLStoreException {
180
		log.debug("  Executing   Query ... " + command);
181

    
182
		Statement st = null;
183
		ResultSet rs = null;
184

    
185
		try{
186
			this.getConnection();
187
 			st = connection.createStatement();
188

    
189
			if (st.execute(command)) {
190

    
191
				rs = st.getResultSet();
192
				CachedRowSet rowset = new CachedRowSetImpl();
193
				rowset.populate(rs);
194

    
195
				return rowset;
196
				//st.close();
197
				//return rs;
198
			} else {
199
				log.error("Fail to execute command " + st.getWarnings());
200
				throw  new SQLStoreException("Fail to execute command " + st.getWarnings());
201

    
202
			}
203

    
204
		} finally {
205
			this.closeResultset(rs);
206
			this.closeStatement(st);
207
			this.closeConnection();
208
		}
209

    
210
	}
211

    
212
	/**
213
	 * Executes the @param  prepared query with the @values as parameters
214
	 * Returns a result set.
215
	 *
216
	 * @param command
217
	 * @param values
218
	 * @return
219
	 * @throws SQLException
220
	 */
221
	public CachedRowSet executeQuery(String command, ArrayList<Object> values) throws SQLException, SQLStoreException {
222
		log.debug("  Executing   Query ...\n" + command +"\n"+values);
223

    
224
		PreparedStatement st = null;
225
		ResultSet rs = null;
226

    
227
		try{
228
			this.getConnection();
229
			st = connection.prepareStatement(command);
230

    
231
			int pos = 1;
232

    
233
			for (Object v : values) {
234

    
235
				st.setObject(pos, v);
236

    
237
				pos++;
238
			}
239

    
240
			if (st.execute()) {
241
				rs = st.getResultSet();
242
				CachedRowSet rowset = new CachedRowSetImpl();
243
				rowset.populate(rs);
244

    
245
				return rowset;
246
				//return rs;
247
			} else {
248
				log.error("Fail to execute command " + st.getWarnings());
249
				throw  new SQLStoreException("Fail to execute command " + st.getWarnings());
250
			}
251

    
252
		} finally {
253
			this.closeResultset(rs);
254
			this.closeStatement(st);
255
			this.closeConnection();
256
		}
257
/*
258

    
259
		ResultSet rs = null;
260
		PreparedStatement st = null;
261
		this.getConnection();
262
		try {
263
			st = connection.prepareStatement(command);
264
			int pos = 1;
265

    
266
			for (Object v : values) {
267

    
268
				st.setObject(pos, v);
269

    
270
				pos++;
271
			}
272
			try {
273
				st.execute();
274
				try {
275
					rs = st.getResultSet();
276
					CachedRowSetImpl rowset = new CachedRowSetImpl();
277
					rowset.populate(rs);
278
					return rowset;
279
				} finally {
280
					try {
281
						rs.close();
282
					} catch (SQLException e) {
283
						log.error("Cannot close result set", e);
284
					}
285
				}
286
			} finally {
287
				try {
288
					st.close();
289
				} catch (SQLException e) {
290
					log.error("Fail to execute command " + st.getWarnings());
291
					log.error("Cannot close statement", e);
292
				}
293
			}
294
		} finally {
295
			try {
296
				log.debug("Closing Connection...");
297
				this.closeConnection();
298
			} catch (SQLException e) {
299
				log.error("Cannot close connection", e);
300
			}
301
		}
302
*/
303

    
304
	}
305

    
306
	/**
307
	 * Executes the @param command Update query
308
	 *
309
	 * @param command
310
	 * @return
311
	 * @throws SQLException
312
	 */
313
	public void executeUpdate(String command) throws SQLException {
314
		log.debug("  Executing   Query ..." + command);
315

    
316
		Statement st = null;
317

    
318
		try{
319
			this.getConnection();
320
 			st = connection.createStatement();
321
			st.executeUpdate(command);
322
			//st.close();
323
		} finally {
324
			this.closeStatement(st);
325
			this.closeConnection();
326
		}
327
	}
328
    public void executeUpdateWithRollback(List<String> commandS)  throws  SQLException{
329
        log.debug("  Executing   Query ..." + commandS);
330
            Statement st = connection.createStatement();
331
            connection.setAutoCommit(false);
332
            for(String command : commandS) {
333
                if(command.equals("EXCEPTION")){
334
                    throw new SQLException("Force rollback ");
335
                }
336
                st.executeUpdate(command);
337
            }
338
            //st.close();
339
            connection.commit();
340
            connection.setAutoCommit(true);
341

    
342
    }
343
	/**
344
	 * Executes the @param command  Prepared Update query  with the
345
	 *
346
	 * @param command
347
	 * @param values
348
	 * @return
349
	 * @throws Exception
350
	 * @values as parameters
351
	 */
352
	public boolean executeUpdate(String command, ArrayList<Object> values) throws SQLException {
353
		log.debug("  Executing   Query ..." + command);
354

    
355
		PreparedStatement st = null;
356

    
357
		try{
358
			this.getConnection();
359

    
360
			st = connection.prepareStatement(command);
361

    
362
			int pos = 1;
363

    
364
			for (Object v : values) {
365

    
366
				st.setObject(pos, v);
367

    
368
				pos++;
369
			}
370

    
371
			boolean executed = st.execute();
372

    
373
			if (executed) {
374
				log.error("Fail to execute update command " + st.getWarnings());
375
				throw new SQLException("Fail to execute update command " + st.getWarnings());
376
			}
377
			return !executed;
378
		} finally {
379
			this.closeStatement(st);
380
			this.closeConnection();
381
		}
382
	}
383

    
384

    
385
	/**
386
	 * Turns autocommit on and off.
387
	 *
388
	 * @param on
389
	 * @throws Exception
390
	 */
391
	public void setautoCommit(boolean on) throws SQLException {
392
			this.connection.setAutoCommit(on);
393
	}
394

    
395

    
396
	/**
397
	 * Creates a serialized string from the ResultSet returned from a query
398
	 *
399
	 * @throws Exception
400
	 */
401
	public String getResults(ResultSet rs) throws SQLException {
402
		String data = new String();
403
		try {
404

    
405

    
406
			ResultSetMetaData rsmd = rs.getMetaData();
407
			while (rs.next()) {
408
				for (int i = 1; i < rsmd.getColumnCount() - 1; i++)
409

    
410
				{
411

    
412
					log.debug(rsmd.getColumnName(i) + "," + rs.getString(i));
413
					data += rsmd.getColumnName(i) + "," + rs.getString(i) + "\n";
414
				}
415

    
416
			}
417
			log.debug(" Generated Data :" + data);
418
			rs.close();
419
			return data;
420

    
421

    
422
		} finally {
423
			this.closeConnection();
424
		}
425

    
426
	}
427

    
428
	private String parseUrl(String url) {
429

    
430
		if (url.endsWith("/")) {
431
			url = url.substring(0, url.lastIndexOf('/'));
432

    
433
		}
434
		url = url.substring(0, url.lastIndexOf('/') + 1);
435
		log.debug(" db url  parsed" + url);
436
		return url;
437
	}
438

    
439
	public String getDbDriver() {
440
		return dbDriver;
441
	}
442

    
443
	public void setDbDriver(String dbDriver) {
444
		this.dbDriver = dbDriver;
445
	}
446

    
447
	public String getDbUrl() {
448
		return dbUrl;
449
	}
450

    
451
	public void setDbUrl(String dbUrl) {
452
		this.dbUrl = dbUrl;
453
	}
454

    
455
	public String getDbUser() {
456
		return dbUser;
457
	}
458

    
459
	public void setDbUser(String dbUser) {
460
		this.dbUser = dbUser;
461
	}
462

    
463
	public String getDbPassword() {
464
		return dbPassword;
465
	}
466

    
467
	public void setDbPassword(String dbPassword) {
468
		this.dbPassword = dbPassword;
469
	}
470

    
471
	public void setConnection(Connection connection) {
472
		this.connection = connection;
473
	}
474
}
(8-8/9)