Project

General

Profile

1
package eu.dnetlib.data.claimsDemo;
2

    
3
import org.apache.log4j.Logger;
4

    
5
import java.sql.*;
6
import java.util.ArrayList;
7
import java.util.List;
8

    
9
/**
10
 * @author eri Sql Store class to connect to the DB backend
11
 */
12

    
13
public class SqlStore {
14

    
15
	private Logger log = Logger.getLogger(this.getClass());
16

    
17
	private String dbUrl;
18
	private String dbUser;
19
	private String dbPassword;
20
	private Connection connection;
21

    
22
	private String dbDriver;
23

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

    
30
	}
31

    
32
	public SqlStore() throws Exception {
33

    
34
	}
35

    
36

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

    
41

    
42
	}
43

    
44
	public void destroy() throws SQLException {
45
		this.closeConnection();
46

    
47
	}
48

    
49
	public void close() throws SQLException {
50
		closeConnection();
51

    
52
	}
53

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

    
66
	}
67

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

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

    
79
	}
80

    
81
	/**
82
	 * Closes Database connections.
83
	 *
84
	 * @throws SQLException
85
	 */
86
	public void closeConnection() throws SQLException {
87

    
88
			if (connection != null) {
89
				connection.close();
90
			}
91

    
92
	}
93

    
94
	/**
95
	 * Executes the @param command stored procedure in the Database. Stored
96
	 * procedure parameters are specified in values.
97
	 *
98
	 * @param command
99
	 * @param values
100
	 * @return
101
	 * @throws SQLException
102
	 */
103
	public ResultSet executeStoredProcedure(String command, ArrayList<String> values) throws SQLException {
104
		java.sql.CallableStatement callableStatement = null;
105
		log.debug("  Executing   Query ..." + command);
106

    
107
			callableStatement = this.connection.prepareCall(command);
108
			int pos = 1;
109

    
110
			for (String v : values) {
111

    
112
				callableStatement.setObject(pos, v);
113

    
114
				pos++;
115
			}
116

    
117
			callableStatement.execute();
118
			return callableStatement.getResultSet();
119

    
120

    
121

    
122
	}
123

    
124
	/**
125
	 * Executes the stored query procedure specified by @param command.
126
	 *
127
	 * @param command
128
	 * @return
129
	 * @throws SQLException
130
	 */
131
	public ResultSet executeStoredProcedure(String command) throws SQLException {
132
		log.debug("  Executing   Query ..." + command);
133
		java.sql.CallableStatement callableStatement = null;
134

    
135
			callableStatement = this.connection.prepareCall(command);
136

    
137
			callableStatement.execute();
138
			return callableStatement.getResultSet();
139

    
140

    
141

    
142
	}
143

    
144
	/**
145
	 * Executes the @param query
146
	 *
147
	 * @param command
148
	 * @return
149
	 * @throws SQLException
150
	 */
151
	public ResultSet executeQuery(String command) throws SQLException, SQLStoreException {
152
		log.debug("  Executing   Query ... " + command);
153
		try{
154
			this.getConnection();
155
 			Statement st = connection.createStatement();
156

    
157
			if (st.execute(command)) {
158

    
159
				ResultSet rs = st.getResultSet();
160
				//st.close();
161
				return rs;
162
			} else {
163
				log.error("Fail to execute command " + st.getWarnings());
164
				throw  new SQLStoreException("Fail to execute command " + st.getWarnings());
165

    
166
			}
167

    
168
		} finally {
169
			this.closeConnection();
170
		}
171

    
172
	}
173

    
174
	/**
175
	 * Executes the @param  prepared query with the @values as parameters
176
	 * Returns a result set.
177
	 *
178
	 * @param command
179
	 * @param values
180
	 * @return
181
	 * @throws SQLException
182
	 */
183
	public ResultSet executeQuery(String command, ArrayList<Object> values) throws SQLException, SQLStoreException {
184
		log.debug("  Executing   Query ..." + command);
185
		try{
186
			this.getConnection();
187
			PreparedStatement st = connection.prepareStatement(command);
188

    
189
			int pos = 1;
190

    
191
			for (Object v : values) {
192

    
193
				st.setObject(pos, v);
194

    
195
				pos++;
196
			}
197

    
198
			if (st.execute()) {
199
				ResultSet rs = st.getResultSet();
200
			//	st.close();
201
				return rs;
202
			} else {
203
				log.error("Fail to execute command " + st.getWarnings());
204
				throw  new SQLStoreException("Fail to execute command " + st.getWarnings());
205
			}
206

    
207
		} finally {
208
			this.closeConnection();
209
		}
210

    
211
	}
212

    
213
	/**
214
	 * Executes the @param command Update query
215
	 *
216
	 * @param command
217
	 * @return
218
	 * @throws SQLException
219
	 */
220
	public void executeUpdate(String command) throws SQLException {
221
		log.debug("  Executing   Query ..." + command);
222
		try{
223
			this.getConnection();
224
 			Statement st = connection.createStatement();
225
			st.executeUpdate(command);
226
			//st.close();
227
		} finally {
228
			this.closeConnection();
229
		}
230
	}
231
    public void executeUpdateWithRollback(List<String> commandS)  throws  SQLException{
232
        log.debug("  Executing   Query ..." + commandS);
233
            Statement st = connection.createStatement();
234
            connection.setAutoCommit(false);
235
            for(String command : commandS) {
236
                if(command.equals("EXCEPTION")){
237
                    throw new SQLException("Force rollback ");
238
                }
239
                st.executeUpdate(command);
240
            }
241
            //st.close();
242
            connection.commit();
243
            connection.setAutoCommit(true);
244

    
245
    }
246
	/**
247
	 * Executes the @param command  Prepared Update query  with the
248
	 *
249
	 * @param command
250
	 * @param values
251
	 * @return
252
	 * @throws Exception
253
	 * @values as parameters
254
	 */
255
	public boolean executeUpdate(String command, ArrayList<Object> values) throws SQLException {
256
		log.debug("  Executing   Query ..." + command);
257
			PreparedStatement st = connection.prepareStatement(command);
258

    
259
			int pos = 1;
260

    
261
			for (Object v : values) {
262

    
263
				st.setObject(pos, v);
264

    
265
				pos++;
266
			}
267

    
268
			boolean executed = st.execute();
269

    
270
			if (executed) {
271
				log.error("Fail to execute update command " + st.getWarnings());
272
				throw new SQLException("Fail to execute update command " + st.getWarnings());
273
			}
274
			return !executed;
275
	}
276

    
277

    
278
	/**
279
	 * Turns autocommit on and off.
280
	 *
281
	 * @param on
282
	 * @throws Exception
283
	 */
284
	public void setautoCommit(boolean on) throws SQLException {
285
			this.connection.setAutoCommit(on);
286
	}
287

    
288

    
289
	/**
290
	 * Creates a serialized string from the ResultSet returned from a query
291
	 *
292
	 * @throws Exception
293
	 */
294
	public String getResults(ResultSet rs) throws SQLException {
295
		String data = new String();
296
		try {
297

    
298

    
299
			ResultSetMetaData rsmd = rs.getMetaData();
300
			while (rs.next()) {
301
				for (int i = 1; i < rsmd.getColumnCount() - 1; i++)
302

    
303
				{
304

    
305
					log.debug(rsmd.getColumnName(i) + "," + rs.getString(i));
306
					data += rsmd.getColumnName(i) + "," + rs.getString(i) + "\n";
307
				}
308

    
309
			}
310
			log.debug(" Generated Data :" + data);
311
			rs.close();
312
			return data;
313

    
314

    
315
		} finally {
316
			this.closeConnection();
317
		}
318

    
319
	}
320

    
321
	private String parseUrl(String url) {
322

    
323
		if (url.endsWith("/")) {
324
			url = url.substring(0, url.lastIndexOf('/'));
325

    
326
		}
327
		url = url.substring(0, url.lastIndexOf('/') + 1);
328
		log.debug(" db url  parsed" + url);
329
		return url;
330
	}
331

    
332
	public String getDbDriver() {
333
		return dbDriver;
334
	}
335

    
336
	public void setDbDriver(String dbDriver) {
337
		this.dbDriver = dbDriver;
338
	}
339

    
340
	public String getDbUrl() {
341
		return dbUrl;
342
	}
343

    
344
	public void setDbUrl(String dbUrl) {
345
		this.dbUrl = dbUrl;
346
	}
347

    
348
	public String getDbUser() {
349
		return dbUser;
350
	}
351

    
352
	public void setDbUser(String dbUser) {
353
		this.dbUser = dbUser;
354
	}
355

    
356
	public String getDbPassword() {
357
		return dbPassword;
358
	}
359

    
360
	public void setDbPassword(String dbPassword) {
361
		this.dbPassword = dbPassword;
362
	}
363

    
364
	public void setConnection(Connection connection) {
365
		this.connection = connection;
366
	}
367
}
(8-8/9)