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 ...\n" + command +"\n"+values);
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
		log.debug("  Executing   Query ..." + command);
258
		try{
259
			this.getConnection();
260

    
261
			PreparedStatement st = connection.prepareStatement(command);
262

    
263
			int pos = 1;
264

    
265
			for (Object v : values) {
266

    
267
				st.setObject(pos, v);
268

    
269
				pos++;
270
			}
271

    
272
			boolean executed = st.execute();
273

    
274
			if (executed) {
275
				log.error("Fail to execute update command " + st.getWarnings());
276
				throw new SQLException("Fail to execute update command " + st.getWarnings());
277
			}
278
			return !executed;
279
		} finally {
280
			this.closeConnection();
281
		}
282
	}
283

    
284

    
285
	/**
286
	 * Turns autocommit on and off.
287
	 *
288
	 * @param on
289
	 * @throws Exception
290
	 */
291
	public void setautoCommit(boolean on) throws SQLException {
292
			this.connection.setAutoCommit(on);
293
	}
294

    
295

    
296
	/**
297
	 * Creates a serialized string from the ResultSet returned from a query
298
	 *
299
	 * @throws Exception
300
	 */
301
	public String getResults(ResultSet rs) throws SQLException {
302
		String data = new String();
303
		try {
304

    
305

    
306
			ResultSetMetaData rsmd = rs.getMetaData();
307
			while (rs.next()) {
308
				for (int i = 1; i < rsmd.getColumnCount() - 1; i++)
309

    
310
				{
311

    
312
					log.debug(rsmd.getColumnName(i) + "," + rs.getString(i));
313
					data += rsmd.getColumnName(i) + "," + rs.getString(i) + "\n";
314
				}
315

    
316
			}
317
			log.debug(" Generated Data :" + data);
318
			rs.close();
319
			return data;
320

    
321

    
322
		} finally {
323
			this.closeConnection();
324
		}
325

    
326
	}
327

    
328
	private String parseUrl(String url) {
329

    
330
		if (url.endsWith("/")) {
331
			url = url.substring(0, url.lastIndexOf('/'));
332

    
333
		}
334
		url = url.substring(0, url.lastIndexOf('/') + 1);
335
		log.debug(" db url  parsed" + url);
336
		return url;
337
	}
338

    
339
	public String getDbDriver() {
340
		return dbDriver;
341
	}
342

    
343
	public void setDbDriver(String dbDriver) {
344
		this.dbDriver = dbDriver;
345
	}
346

    
347
	public String getDbUrl() {
348
		return dbUrl;
349
	}
350

    
351
	public void setDbUrl(String dbUrl) {
352
		this.dbUrl = dbUrl;
353
	}
354

    
355
	public String getDbUser() {
356
		return dbUser;
357
	}
358

    
359
	public void setDbUser(String dbUser) {
360
		this.dbUser = dbUser;
361
	}
362

    
363
	public String getDbPassword() {
364
		return dbPassword;
365
	}
366

    
367
	public void setDbPassword(String dbPassword) {
368
		this.dbPassword = dbPassword;
369
	}
370

    
371
	public void setConnection(Connection connection) {
372
		this.connection = connection;
373
	}
374
}
(8-8/9)