Project

General

Profile

1
package eu.dnetlib.data.claims.sql;
2

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

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

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

    
16
public class SqlStore {
17

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

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

    
25
	private String dbDriver;
26

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

    
33
	}
34

    
35
	public SqlStore() throws Exception {
36

    
37
	}
38

    
39

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

    
44

    
45
	}
46

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

    
50
	}
51

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

    
55
	}
56

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

    
69
	}
70

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

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

    
82
	}
83

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

    
95
	}
96

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

    
108
	}
109

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

    
121
	}
122

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

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

    
139
			for (String v : values) {
140

    
141
				callableStatement.setObject(pos, v);
142

    
143
				pos++;
144
			}
145

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

    
149

    
150

    
151
	}
152

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

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

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

    
169

    
170

    
171
	}
172

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

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

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

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

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

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

    
203
			}
204

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

    
211
	}
212

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

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

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

    
232
			int pos = 1;
233

    
234
			for (Object v : values) {
235

    
236
				st.setObject(pos, v);
237

    
238
				pos++;
239
			}
240

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

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

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

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

    
267
			for (Object v : values) {
268

    
269
				st.setObject(pos, v);
270

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

    
305
	}
306

    
307
	/**
308
	 * Executes the @param command Update query
309
	 *
310
	 * @param command
311
	 * @return
312
	 * @throws SQLException
313
	 */
314
	public void executeUpdate(String command) throws SQLException {
315
		log.debug("  Executing   Query ..." + command.substring(0,(command.length()>150?150:command.length())));
316

    
317
		Statement st = null;
318

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

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

    
356
		PreparedStatement st = null;
357

    
358
		try{
359
			this.getConnection();
360

    
361
			st = connection.prepareStatement(command);
362

    
363
			int pos = 1;
364

    
365
			for (Object v : values) {
366

    
367
				st.setObject(pos, v);
368

    
369
				pos++;
370
			}
371

    
372
			boolean executed = st.execute();
373

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

    
385

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

    
396

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

    
406

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

    
411
				{
412

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

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

    
422

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

    
427
	}
428

    
429
	private String parseUrl(String url) {
430

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

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

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

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

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

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

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

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

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

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

    
472
	public void setConnection(Connection connection) {
473
		this.connection = connection;
474
	}
475
}
(3-3/3)