1
|
package eu.dnetlib.enabling.database.utils;
|
2
|
|
3
|
import java.io.StringReader;
|
4
|
import java.sql.*;
|
5
|
import java.sql.Date;
|
6
|
import java.text.ParseException;
|
7
|
import java.text.SimpleDateFormat;
|
8
|
import java.util.*;
|
9
|
import java.util.concurrent.ArrayBlockingQueue;
|
10
|
import java.util.concurrent.BlockingQueue;
|
11
|
import java.util.concurrent.Executors;
|
12
|
import java.util.concurrent.TimeUnit;
|
13
|
import java.util.concurrent.atomic.AtomicReference;
|
14
|
import java.util.regex.Pattern;
|
15
|
import javax.sql.DataSource;
|
16
|
|
17
|
import com.google.common.collect.Lists;
|
18
|
import com.google.common.collect.Queues;
|
19
|
import com.google.common.collect.Sets;
|
20
|
import eu.dnetlib.enabling.database.DataSourceFactory;
|
21
|
import eu.dnetlib.enabling.database.TransactionTemplateFactory;
|
22
|
import eu.dnetlib.enabling.database.objects.DnetDatabase;
|
23
|
import eu.dnetlib.enabling.database.rmi.DatabaseException;
|
24
|
import eu.dnetlib.miscutils.datetime.DateUtils;
|
25
|
import eu.dnetlib.miscutils.functional.string.Sanitizer;
|
26
|
import org.apache.commons.lang.BooleanUtils;
|
27
|
import org.apache.commons.logging.Log;
|
28
|
import org.apache.commons.logging.LogFactory;
|
29
|
import org.apache.velocity.app.VelocityEngine;
|
30
|
import org.dom4j.Document;
|
31
|
import org.dom4j.DocumentHelper;
|
32
|
import org.dom4j.Element;
|
33
|
import org.dom4j.Node;
|
34
|
import org.dom4j.io.SAXReader;
|
35
|
import org.joda.time.DateTime;
|
36
|
import org.joda.time.format.ISODateTimeFormat;
|
37
|
import org.springframework.beans.factory.annotation.Required;
|
38
|
import org.springframework.dao.DataAccessException;
|
39
|
import org.springframework.jdbc.core.JdbcTemplate;
|
40
|
import org.springframework.jdbc.core.RowCallbackHandler;
|
41
|
import org.springframework.jdbc.support.rowset.SqlRowSet;
|
42
|
import org.springframework.transaction.TransactionStatus;
|
43
|
import org.springframework.transaction.support.TransactionCallback;
|
44
|
import org.springframework.transaction.support.TransactionTemplate;
|
45
|
import org.springframework.ui.velocity.VelocityEngineUtils;
|
46
|
|
47
|
public class DatabaseUtils {
|
48
|
|
49
|
public static final String DNET_RESOURCE_ID_FIELD = "_dnet_resource_identifier_";
|
50
|
public static final int BLOCKING_QUEUE_TIMEOUT = 300;
|
51
|
private static final String SQL_DATE_FORMAT = "yyyy-MM-dd";
|
52
|
private static final Log log = LogFactory.getLog(DatabaseUtils.class); // NOPMD by marko on 11/24/08 5:02 PM
|
53
|
private static final int BLOCKING_QUEUE_SIZE = 200;
|
54
|
private static final Set<String> TRUE_VALUES = Sets.newHashSet("true", "t", "yes", "y", "vero", "v");
|
55
|
private static final Set<String> FALSE_VALUES = Sets.newHashSet("false", "f", "no", "n", "falso");
|
56
|
private DataSourceFactory dataSourceFactory;
|
57
|
private JdbcTemplateFactory jdbcTemplateFactory;
|
58
|
private TransactionTemplateFactory transactionTemplateFactory;
|
59
|
private String defaultDB;
|
60
|
private VelocityEngine velocityEngine;
|
61
|
private String dbPrefix;
|
62
|
private int numbersOfRecordsForTransaction;
|
63
|
|
64
|
public List<String> listCommonDBTables(final String database) throws DatabaseException {
|
65
|
String query =
|
66
|
"SELECT table_name FROM information_schema.tables " + "WHERE table_schema = 'public' " + "AND table_type != 'VIEW' "
|
67
|
+ "AND table_name NOT LIKE '%_log'";
|
68
|
return getTypedListFromSql(database, query, String.class);
|
69
|
}
|
70
|
|
71
|
public List<String> listCommonDBViews(final String database) throws DatabaseException {
|
72
|
String query =
|
73
|
"SELECT table_name FROM information_schema.tables " + "WHERE table_schema = 'public' " + "AND table_type = 'VIEW' "
|
74
|
+ "AND table_name NOT LIKE '%_log'";
|
75
|
return getTypedListFromSql(database, query, String.class);
|
76
|
}
|
77
|
|
78
|
public Map<String, TableDates> getTableDatesForDB(final String db) throws DatabaseException {
|
79
|
Map<String, TableDates> res = new HashMap<String, TableDates>();
|
80
|
|
81
|
for (String table : listCommonDBTables(db)) {
|
82
|
try {
|
83
|
TableDates dates = new TableDates();
|
84
|
|
85
|
String query =
|
86
|
"select lastinsert, lastupdate, lastdelete from " + "(select max(date) as lastinsert from " + table
|
87
|
+ "_log where operation='insert') as t1, " + "(select max(date) as lastupdate from " + table
|
88
|
+ "_log where operation='update') as t2, " + "(select max(date) as lastdelete from " + table
|
89
|
+ "_log where operation='delete') as t3";
|
90
|
|
91
|
SqlRowSet srs = executeSql(db, query, SqlRowSet.class);
|
92
|
if (srs.next()) {
|
93
|
dates.setLastInsert(srs.getDate("lastinsert"));
|
94
|
dates.setLastUpdate(srs.getDate("lastupdate"));
|
95
|
dates.setLastDelete(srs.getDate("lastdelete"));
|
96
|
}
|
97
|
res.put(table, dates);
|
98
|
} catch (Exception e) {
|
99
|
log.warn("Error obtaing dates for table " + table, e);
|
100
|
}
|
101
|
}
|
102
|
return res;
|
103
|
}
|
104
|
|
105
|
public List<DnetDatabase> listAllDatabases() throws DatabaseException {
|
106
|
final String query =
|
107
|
"SELECT d.datname AS db, COALESCE(dsc.description,'')='isManaged' AS managed FROM pg_database d LEFT OUTER JOIN pg_shdescription dsc ON (d.oid = dsc.objoid) WHERE d.datname LIKE '"
|
108
|
+ dbPrefix + "%' ORDER BY d.datname DESC";
|
109
|
final JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(defaultDB);
|
110
|
|
111
|
final List<DnetDatabase> list = Lists.newArrayList();
|
112
|
for (Map<String, Object> map : jdbcTemplate.queryForList(query)) {
|
113
|
list.add(new DnetDatabase(map.get("db").toString(), Boolean.parseBoolean(map.get("managed").toString())));
|
114
|
}
|
115
|
return list;
|
116
|
|
117
|
}
|
118
|
|
119
|
public <T> List<T> getTypedListFromSql(final String dbName, final String query, final Class<T> clazz) throws DatabaseException {
|
120
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
|
121
|
|
122
|
try {
|
123
|
List<T> list = new ArrayList<T>();
|
124
|
for (Object obj : jdbcTemplate.queryForList(query, clazz)) {
|
125
|
list.add(clazz.cast(obj));
|
126
|
}
|
127
|
return list;
|
128
|
} catch (DataAccessException e) {
|
129
|
throw new DatabaseException(e);
|
130
|
}
|
131
|
}
|
132
|
|
133
|
public List<String> getSimpleListFromSql(final String dbName, final String query) throws DatabaseException {
|
134
|
|
135
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
|
136
|
|
137
|
try {
|
138
|
List<String> list = new ArrayList<String>();
|
139
|
for (Object obj : jdbcTemplate.queryForList(query)) {
|
140
|
list.add(obj.toString());
|
141
|
}
|
142
|
return list;
|
143
|
} catch (DataAccessException e) {
|
144
|
throw new DatabaseException(e);
|
145
|
}
|
146
|
}
|
147
|
|
148
|
public void executeSql(final String db, final String query) throws DatabaseException {
|
149
|
executeSql(db, query, Void.class);
|
150
|
}
|
151
|
|
152
|
@SuppressWarnings("unchecked")
|
153
|
public <T> T executeSql(final String dbName, final String query, final Class<T> clazz) throws DatabaseException {
|
154
|
|
155
|
final JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
|
156
|
try {
|
157
|
if (clazz == Integer.class) return (T) jdbcTemplate.queryForObject(query, Integer.class);
|
158
|
else if (clazz == List.class) return (T) jdbcTemplate.queryForList(query);
|
159
|
else if (clazz == Map.class) return (T) jdbcTemplate.queryForMap(query);
|
160
|
else if (clazz == SqlRowSet.class) return (T) jdbcTemplate.queryForRowSet(query);
|
161
|
else if (clazz == BlockingQueue.class) {
|
162
|
log.debug("Creating Queue");
|
163
|
|
164
|
final ArrayBlockingQueue<Map<String, Object>> q = Queues.newArrayBlockingQueue(BLOCKING_QUEUE_SIZE);
|
165
|
|
166
|
Runnable run = new Runnable() {
|
167
|
|
168
|
@Override
|
169
|
public void run() {
|
170
|
try {
|
171
|
jdbcTemplate.query(query, getRowCallback(q));
|
172
|
} catch (Throwable e) {
|
173
|
log.error("Exception executing SQL", e);
|
174
|
throw new RuntimeException(e);
|
175
|
}
|
176
|
try {
|
177
|
// An empty Map indicates the end of the resultset
|
178
|
q.offer(new HashMap<String, Object>(), BLOCKING_QUEUE_TIMEOUT, TimeUnit.SECONDS);
|
179
|
} catch (InterruptedException e) {
|
180
|
log.error("Error putting LAST element in queue");
|
181
|
throw new RuntimeException(e);
|
182
|
}
|
183
|
log.debug(" -- End of Sql Resultset");
|
184
|
}
|
185
|
|
186
|
private RowCallbackHandler getRowCallback(final BlockingQueue<Map<String, Object>> q) {
|
187
|
return new RowCallbackHandler() {
|
188
|
|
189
|
@Override
|
190
|
public void processRow(final ResultSet rs) throws SQLException {
|
191
|
|
192
|
ResultSetMetaData md = rs.getMetaData();
|
193
|
Map<String, Object> row = new HashMap<String, Object>();
|
194
|
for (int i = 1; i <= md.getColumnCount(); i++) {
|
195
|
row.put(md.getColumnName(i), rs.getObject(i));
|
196
|
}
|
197
|
try {
|
198
|
if (!rs.isClosed() && !q.offer(row, BLOCKING_QUEUE_TIMEOUT, TimeUnit.SECONDS)) {
|
199
|
log.warn("The consumer doesn't consume my queue, I stop");
|
200
|
rs.close();
|
201
|
return;
|
202
|
}
|
203
|
log.debug("Putted element in queue");
|
204
|
} catch (InterruptedException e) {
|
205
|
log.error("Error putting element in queue");
|
206
|
throw new RuntimeException(e);
|
207
|
}
|
208
|
}
|
209
|
};
|
210
|
}
|
211
|
};
|
212
|
Executors.newSingleThreadExecutor().submit(run);
|
213
|
|
214
|
log.debug("Returned Queue");
|
215
|
|
216
|
return (T) q;
|
217
|
} else {
|
218
|
jdbcTemplate.update(query);
|
219
|
return null;
|
220
|
}
|
221
|
} catch (Throwable e) {
|
222
|
throw new DatabaseException(e);
|
223
|
}
|
224
|
}
|
225
|
|
226
|
public boolean contains(final String db, final String table, final String column, final String value) throws DatabaseException {
|
227
|
String query = "";
|
228
|
try {
|
229
|
verifyParameters(db, table, column);
|
230
|
query = "SELECT " + column + " FROM " + table + " WHERE " + column + " = '" + value + "'";
|
231
|
List<String> res = getSimpleListFromSql(db, query);
|
232
|
return res != null && res.size() > 0;
|
233
|
} catch (Throwable e) {
|
234
|
throw new DatabaseException("Error performing SQL: " + query, e);
|
235
|
}
|
236
|
}
|
237
|
|
238
|
public List<Map<?, ?>> describeTable(final String database, final String table) throws DatabaseException {
|
239
|
verifyParameters(database, table);
|
240
|
|
241
|
try {
|
242
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
243
|
List<Map<?, ?>> response = new ArrayList<Map<?, ?>>();
|
244
|
String query = "SELECT * FROM information_schema.columns WHERE table_name = ?";
|
245
|
|
246
|
for (Object o : jdbcTemplate.queryForList(query, new Object[] { table })) {
|
247
|
if (o instanceof Map<?, ?>) {
|
248
|
response.add((Map<?, ?>) o);
|
249
|
}
|
250
|
}
|
251
|
return response;
|
252
|
} catch (DataAccessException e) {
|
253
|
throw new DatabaseException(e);
|
254
|
}
|
255
|
}
|
256
|
|
257
|
public String dumpTableAsXML(final String db, final String t) throws DatabaseException {
|
258
|
return dumpTableAsDoc(db, t).asXML();
|
259
|
}
|
260
|
|
261
|
public Document dumpTableAsDoc(final String db, final String t) throws DatabaseException {
|
262
|
Document doc = DocumentHelper.createDocument();
|
263
|
|
264
|
Element root = doc.addElement("DB_TABLE");
|
265
|
Element head = root.addElement("HEADER");
|
266
|
|
267
|
head.addElement("DATABASE").addAttribute("value", db);
|
268
|
head.addElement("TABLE").addAttribute("value", t);
|
269
|
head.addElement("DATE").addAttribute("value", DateUtils.now_ISO8601());
|
270
|
|
271
|
Element body = root.addElement("BODY");
|
272
|
for (Document d : dumpTableAsList(db, t)) {
|
273
|
body.add(d.getRootElement());
|
274
|
}
|
275
|
return doc;
|
276
|
}
|
277
|
|
278
|
public List<Document> dumpTableAsList(final String db, final String t) throws DatabaseException {
|
279
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(db);
|
280
|
|
281
|
List<Document> list = new ArrayList<Document>();
|
282
|
for (Object o : jdbcTemplate.queryForList("SELECT * FROM " + t)) {
|
283
|
if (o instanceof Map<?, ?>) {
|
284
|
list.add(rowToDocument((Map<?, ?>) o));
|
285
|
}
|
286
|
}
|
287
|
return list;
|
288
|
}
|
289
|
|
290
|
public Document rowToDocument(final Map<?, ?> map) throws DatabaseException {
|
291
|
Document doc = DocumentHelper.createDocument();
|
292
|
|
293
|
Element row = doc.addElement("ROW");
|
294
|
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
295
|
Element col = row.addElement("FIELD");
|
296
|
col.addAttribute("name", "" + entry.getKey());
|
297
|
addValue(col, entry.getValue());
|
298
|
}
|
299
|
return doc;
|
300
|
}
|
301
|
|
302
|
public Document getRowByResourceId(final String database, final String table, final String resourceId) throws DatabaseException {
|
303
|
verifyParameters(database, table);
|
304
|
|
305
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
306
|
String query = "SELECT * FROM " + table + " WHERE " + DNET_RESOURCE_ID_FIELD + "=?";
|
307
|
|
308
|
Map<?, ?> map = jdbcTemplate.queryForMap(query, resourceId);
|
309
|
Document doc = DocumentHelper.createDocument();
|
310
|
|
311
|
Element root = doc.addElement("DB_RECORD");
|
312
|
Element head = root.addElement("HEADER");
|
313
|
head.addElement("RESOURCE_IDENTIFIER").addAttribute("value", resourceId);
|
314
|
head.addElement("DATABASE").addAttribute("value", database);
|
315
|
head.addElement("TABLE").addAttribute("value", table);
|
316
|
head.addElement("DATE").addAttribute("value", DateUtils.now_ISO8601());
|
317
|
|
318
|
Element body = root.addElement("BODY");
|
319
|
|
320
|
Element row = body.addElement("ROW");
|
321
|
|
322
|
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
323
|
Element col = row.addElement("FIELD");
|
324
|
col.addAttribute("name", "" + entry.getKey());
|
325
|
addValue(col, entry.getValue());
|
326
|
}
|
327
|
|
328
|
return doc;
|
329
|
}
|
330
|
|
331
|
private void addValue(final Element elem, final Object value) throws DatabaseException {
|
332
|
if (value instanceof Array) {
|
333
|
try {
|
334
|
for (Object o : (Object[]) ((Array) value).getArray()) {
|
335
|
addValue(elem.addElement("ITEM"), o);
|
336
|
}
|
337
|
} catch (Exception e) {
|
338
|
throw new DatabaseException("Error procsessing a Array", e);
|
339
|
}
|
340
|
} else if (value != null) {
|
341
|
elem.addText(Sanitizer.sanitize(value.toString()));
|
342
|
} else {
|
343
|
elem.addAttribute("isNull", "true");
|
344
|
}
|
345
|
}
|
346
|
|
347
|
private void verifyParameters(final String... params) throws DatabaseException {
|
348
|
Pattern pattern = Pattern.compile("\\w{1,128}");
|
349
|
|
350
|
for (String p : params) {
|
351
|
log.debug("TESTING SQL PARAM:" + p);
|
352
|
if (p == null) throw new DatabaseException("Parameter is null");
|
353
|
else if (!pattern.matcher(p).matches()) throw new DatabaseException("Parameter [" + p + "] contains an invalid character");
|
354
|
else {
|
355
|
log.debug("TEST OK");
|
356
|
}
|
357
|
}
|
358
|
}
|
359
|
|
360
|
public void importFromIterable(final String db, final Iterable<String> iterable) throws DatabaseException {
|
361
|
verifyParameters(db);
|
362
|
|
363
|
final DataSource dataSource = dataSourceFactory.createDataSource(db);
|
364
|
final JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dataSource);
|
365
|
final TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(dataSource);
|
366
|
|
367
|
int counterTotal = 0;
|
368
|
|
369
|
long start = DateUtils.now();
|
370
|
|
371
|
List<GenericRow> rows = new ArrayList<GenericRow>();
|
372
|
for (String prof : iterable) {
|
373
|
rows.addAll(obtainListOfRows(prof));
|
374
|
if (rows.size() > numbersOfRecordsForTransaction) {
|
375
|
counterTotal += rows.size();
|
376
|
importTransaction(jdbcTemplate, transactionTemplate, rows);
|
377
|
rows.clear();
|
378
|
}
|
379
|
}
|
380
|
counterTotal += rows.size();
|
381
|
importTransaction(jdbcTemplate, transactionTemplate, rows);
|
382
|
|
383
|
long end = DateUtils.now();
|
384
|
|
385
|
log.info("**********************************************************");
|
386
|
log.info("Processed " + counterTotal + " rows in " + ((end - start) / 1000) + " seconds");
|
387
|
log.info("**********************************************************");
|
388
|
}
|
389
|
|
390
|
private void importTransaction(final JdbcTemplate jdbcTemplate, final TransactionTemplate transactionTemplate, List<GenericRow> rows)
|
391
|
throws DatabaseException {
|
392
|
if (rows != null && rows.size() > 0) {
|
393
|
importTransactionInternal(jdbcTemplate, transactionTemplate, rows);
|
394
|
}
|
395
|
}
|
396
|
|
397
|
private List<GenericRow> importTransactionInternal(final JdbcTemplate jdbcTemplate,
|
398
|
final TransactionTemplate transactionTemplate,
|
399
|
final List<GenericRow> rows) throws DatabaseException {
|
400
|
|
401
|
final AtomicReference<DatabaseException> error = new AtomicReference<DatabaseException>();
|
402
|
|
403
|
try {
|
404
|
return transactionTemplate.execute(new TransactionCallback<List<GenericRow>>() {
|
405
|
|
406
|
@Override
|
407
|
public List<GenericRow> doInTransaction(final TransactionStatus status) {
|
408
|
final List<GenericRow> ok = Lists.newArrayList();
|
409
|
try {
|
410
|
for (GenericRow row : rows) {
|
411
|
if (row.isToDelete()) {
|
412
|
deleteRow(jdbcTemplate, row.getTable(), row.getFields());
|
413
|
} else {
|
414
|
addOrUpdateRow(jdbcTemplate, row.getTable(), row.getFields());
|
415
|
}
|
416
|
ok.add(row);
|
417
|
}
|
418
|
} catch (DatabaseException e) {
|
419
|
log.warn("Transaction failed", e);
|
420
|
status.setRollbackOnly();
|
421
|
error.set(e);
|
422
|
}
|
423
|
return ok;
|
424
|
}
|
425
|
});
|
426
|
} finally {
|
427
|
if (error.get() != null) {
|
428
|
throw error.get();
|
429
|
}
|
430
|
}
|
431
|
}
|
432
|
|
433
|
protected void addOrUpdateRow(final JdbcTemplate jdbcTemplate, final String table, final Map<String, Object> rowFields) throws DatabaseException {
|
434
|
try {
|
435
|
|
436
|
if (log.isDebugEnabled()) {
|
437
|
log.debug("Adding or updating element to table " + table);
|
438
|
}
|
439
|
verifyParameters(table);
|
440
|
verifyParameters(rowFields.keySet().toArray(new String[rowFields.size()]));
|
441
|
|
442
|
String fields = "";
|
443
|
String values = "";
|
444
|
List<Object> list = new ArrayList<Object>();
|
445
|
|
446
|
for (Map.Entry<String, Object> e : rowFields.entrySet()) {
|
447
|
if (!fields.isEmpty()) {
|
448
|
fields += ",";
|
449
|
}
|
450
|
fields += e.getKey();
|
451
|
if (!values.isEmpty()) {
|
452
|
values += ",";
|
453
|
}
|
454
|
values += "?";
|
455
|
list.add(e.getValue());
|
456
|
}
|
457
|
|
458
|
int count = 0;
|
459
|
if (rowFields.containsKey(DNET_RESOURCE_ID_FIELD)) {
|
460
|
List<Object> list2 = new ArrayList<Object>();
|
461
|
list2.addAll(list);
|
462
|
list2.add(rowFields.get(DNET_RESOURCE_ID_FIELD));
|
463
|
count =
|
464
|
jdbcTemplate.update("UPDATE " + table + " SET (" + fields + ") = (" + values + ") WHERE " + DNET_RESOURCE_ID_FIELD + "=?",
|
465
|
list2.toArray());
|
466
|
}
|
467
|
if (count == 0) {
|
468
|
jdbcTemplate.update("INSERT INTO " + table + " (" + fields + ") VALUES (" + values + ")", list.toArray());
|
469
|
}
|
470
|
} catch (final Exception e) {
|
471
|
throw new DatabaseException("Error adding or updating record", e);
|
472
|
}
|
473
|
}
|
474
|
|
475
|
protected void deleteRow(final JdbcTemplate jdbcTemplate, final String table, final Map<String, Object> rowFields) throws DatabaseException {
|
476
|
if (log.isDebugEnabled()) {
|
477
|
log.debug("Deleting element from table " + table);
|
478
|
}
|
479
|
verifyParameters(table);
|
480
|
verifyParameters(rowFields.keySet().toArray(new String[rowFields.size()]));
|
481
|
|
482
|
List<Object> list = new ArrayList<Object>();
|
483
|
|
484
|
String where = "";
|
485
|
|
486
|
for (Map.Entry<String, Object> e : rowFields.entrySet()) {
|
487
|
if (!where.isEmpty()) {
|
488
|
where += " AND ";
|
489
|
}
|
490
|
where += e.getKey() + "=?";
|
491
|
list.add(e.getValue());
|
492
|
}
|
493
|
|
494
|
if (where.isEmpty()) throw new DatabaseException("Delete condition is empty");
|
495
|
int n = jdbcTemplate.update("DELETE FROM " + table + " WHERE " + where, list.toArray());
|
496
|
|
497
|
if (log.isDebugEnabled()) {
|
498
|
log.debug("Number of Deleted records: " + n);
|
499
|
}
|
500
|
}
|
501
|
|
502
|
public void deleteRowByResourceId(final String database, final String table, final String resourceIdentifier) throws DatabaseException {
|
503
|
verifyParameters(database, table, resourceIdentifier);
|
504
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
505
|
jdbcTemplate.update("DELETE FROM " + table + " WHERE " + DNET_RESOURCE_ID_FIELD + "=?", resourceIdentifier);
|
506
|
}
|
507
|
|
508
|
public void clearTable(final String database, final String table) throws DatabaseException {
|
509
|
verifyParameters(database, table);
|
510
|
|
511
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
512
|
jdbcTemplate.update("DELETE FROM " + table);
|
513
|
}
|
514
|
|
515
|
public void prepareManagementOfTable(final String database, final String table) throws DatabaseException {
|
516
|
verifyParameters(database, table);
|
517
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
518
|
|
519
|
if (!isManagedTable(jdbcTemplate, table)) {
|
520
|
jdbcTemplate.update(getSQLFromTemplate("manageTable", database, table, null));
|
521
|
log.info("Added management of table " + table);
|
522
|
}
|
523
|
}
|
524
|
|
525
|
public void removeManagementOfTable(final String database, final String table) throws DatabaseException {
|
526
|
verifyParameters(database, table);
|
527
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
528
|
|
529
|
if (isManagedTable(jdbcTemplate, table)) {
|
530
|
jdbcTemplate.update(getSQLFromTemplate("unmanageTable", database, table, null));
|
531
|
log.info("Removed management of table " + table);
|
532
|
}
|
533
|
}
|
534
|
|
535
|
public boolean isManagedTable(final String database, final String table) throws DatabaseException {
|
536
|
verifyParameters(database, table);
|
537
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
538
|
return isManagedTable(jdbcTemplate, table);
|
539
|
}
|
540
|
|
541
|
private boolean isManagedTable(final JdbcTemplate jdbcTemplate, final String table) {
|
542
|
return jdbcTemplate.queryForObject("SELECT count(*) FROM information_schema.columns WHERE table_name = ? AND column_name = ?", Integer.class,
|
543
|
table, DNET_RESOURCE_ID_FIELD) == 1;
|
544
|
}
|
545
|
|
546
|
public boolean isLoggedTable(final String database, final String table) throws DatabaseException {
|
547
|
verifyParameters(database, table);
|
548
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
549
|
return isLoggedTable(jdbcTemplate, table);
|
550
|
}
|
551
|
|
552
|
private boolean isLoggedTable(final JdbcTemplate jdbcTemplate, final String table) {
|
553
|
return jdbcTemplate.queryForObject("SELECT count(*) FROM information_schema.tables WHERE table_name = ?", Integer.class,
|
554
|
table + "_log") == 1;
|
555
|
}
|
556
|
|
557
|
public String getDefaultDnetIdentifier(final String database, final String table) throws DatabaseException {
|
558
|
verifyParameters(database, table);
|
559
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(database);
|
560
|
if (isManagedTable(jdbcTemplate, table)) return jdbcTemplate.queryForObject(
|
561
|
"SELECT column_default FROM information_schema.columns WHERE table_name = ? AND column_name = ?", new Object[] {
|
562
|
table, DNET_RESOURCE_ID_FIELD }, String.class);
|
563
|
return "";
|
564
|
}
|
565
|
|
566
|
public void reassignDefaultDnetIdentifiers(final String db) throws DatabaseException {
|
567
|
for (String t : listCommonDBTables(db)) {
|
568
|
reassignDefaultDnetIdentifiers(db, t);
|
569
|
}
|
570
|
}
|
571
|
|
572
|
public void reassignDefaultDnetIdentifiers(final String db, final String t) throws DatabaseException {
|
573
|
if (!isManagedTable(db, t)) return;
|
574
|
|
575
|
SqlRowSet rows =
|
576
|
executeSql(db, "SELECT pg_attribute.attname as pkey FROM pg_index, pg_class, pg_attribute " + "WHERE pg_class.oid = '" + t + "'::regclass "
|
577
|
+ "AND indrelid = pg_class.oid " + "AND pg_attribute.attrelid = pg_class.oid "
|
578
|
+ "AND pg_attribute.attnum = any(pg_index.indkey) AND indisprimary " + "ORDER BY pkey", SqlRowSet.class);
|
579
|
|
580
|
String defaultValue = "";
|
581
|
while (rows.next()) {
|
582
|
if (!defaultValue.isEmpty()) {
|
583
|
defaultValue += "||'@@'||";
|
584
|
}
|
585
|
defaultValue += rows.getString("pkey");
|
586
|
}
|
587
|
executeSql(db, "UPDATE " + t + " SET " + DatabaseUtils.DNET_RESOURCE_ID_FIELD + " = " + defaultValue);
|
588
|
log.info("Reassigned dnetId for table " + t);
|
589
|
}
|
590
|
|
591
|
public String getSQLFromTemplate(final String sqlTemplate, final String db, final String table, Map<String, Object> map) {
|
592
|
if (map == null) {
|
593
|
map = new HashMap<String, Object>();
|
594
|
}
|
595
|
|
596
|
map.put("mainDB", defaultDB);
|
597
|
map.put("db", db);
|
598
|
map.put("table", table);
|
599
|
map.put("idField", DNET_RESOURCE_ID_FIELD);
|
600
|
|
601
|
return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "eu/dnetlib/enabling/database/velocity/" + sqlTemplate + ".sql.vm", "UTF-8", map);
|
602
|
}
|
603
|
|
604
|
public List<GenericRow> obtainListOfRows(final String xml) throws DatabaseException {
|
605
|
try {
|
606
|
Document doc = new SAXReader().read(new StringReader(xml));
|
607
|
|
608
|
List<GenericRow> list = new ArrayList<GenericRow>();
|
609
|
|
610
|
for (Object or : doc.selectNodes("//ROW")) {
|
611
|
Element row = (Element) or;
|
612
|
|
613
|
String table = row.valueOf("@table");
|
614
|
|
615
|
if ((table == null) || table.isEmpty()) throw new DatabaseException("Attribute table is missing in XSLT");
|
616
|
|
617
|
boolean toDelete = "deleted".equals(row.valueOf("@status"));
|
618
|
|
619
|
Map<String, Object> fields = new HashMap<String, Object>();
|
620
|
|
621
|
for (Object of : row.selectNodes("./FIELD")) {
|
622
|
Node node = (Node) of;
|
623
|
String key = node.valueOf("@name");
|
624
|
String type = node.valueOf("@type");
|
625
|
String format = node.valueOf("@format");
|
626
|
String valueS = node.getText().trim();
|
627
|
|
628
|
if ((key != null) && !key.isEmpty()) {
|
629
|
Object value = valueS;
|
630
|
if (type != null) {
|
631
|
|
632
|
try {
|
633
|
// probably an empty string in a typed field means null
|
634
|
if ("".equals(valueS)) {
|
635
|
value = null;
|
636
|
} else if (type.equals("int")) {
|
637
|
value = Integer.parseInt(valueS);
|
638
|
} else if (type.equals("float")) {
|
639
|
value = Float.parseFloat(valueS);
|
640
|
} else if (type.equals("boolean")) {
|
641
|
value = parseBoolean(valueS);
|
642
|
} else if (type.equals("date")) {
|
643
|
value = parseDate(valueS, format);
|
644
|
} else if (type.equals("iso8601Date")) {
|
645
|
DateTime date = ISODateTimeFormat.dateTimeParser().parseDateTime(valueS);
|
646
|
value = date.toDate();
|
647
|
// value = new DateUtils().parse(valueS);
|
648
|
}
|
649
|
} catch (IllegalArgumentException e) {
|
650
|
log.fatal("cannot convert '" + valueS + "' to " + type, e);
|
651
|
throw e;
|
652
|
}
|
653
|
}
|
654
|
fields.put(key, value);
|
655
|
}
|
656
|
}
|
657
|
|
658
|
list.add(new GenericRow(table, fields, toDelete));
|
659
|
}
|
660
|
return list;
|
661
|
} catch (Exception e) {
|
662
|
log.error("Error obtaining list of rows from xml: " + xml);
|
663
|
throw new DatabaseException(e);
|
664
|
}
|
665
|
}
|
666
|
|
667
|
protected boolean parseBoolean(final String s) {
|
668
|
if (TRUE_VALUES.contains(s.toLowerCase().trim())) return true;
|
669
|
if (FALSE_VALUES.contains(s.toLowerCase().trim())) return false;
|
670
|
|
671
|
return BooleanUtils.toBoolean(s);
|
672
|
}
|
673
|
|
674
|
public void setManaged(final String dbName, final boolean managed) throws DatabaseException {
|
675
|
verifyParameters(dbName);
|
676
|
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
|
677
|
if (managed) {
|
678
|
jdbcTemplate.update("COMMENT ON DATABASE " + dbName + " IS 'isManaged'");
|
679
|
} else {
|
680
|
jdbcTemplate.update("COMMENT ON DATABASE " + dbName + " IS NULL");
|
681
|
}
|
682
|
}
|
683
|
|
684
|
// public for testing
|
685
|
public Date parseDate(final String date, String format) {
|
686
|
if ((format == null) || format.isEmpty()) {
|
687
|
format = SQL_DATE_FORMAT;
|
688
|
}
|
689
|
try {
|
690
|
java.util.Date parsed = new SimpleDateFormat(format).parse(date);
|
691
|
String ret = new SimpleDateFormat(SQL_DATE_FORMAT).format(parsed);
|
692
|
return Date.valueOf(ret);
|
693
|
} catch (ParseException e) {
|
694
|
return null;
|
695
|
}
|
696
|
}
|
697
|
|
698
|
@Required
|
699
|
public void setVelocityEngine(final VelocityEngine velocityEngine) {
|
700
|
this.velocityEngine = velocityEngine;
|
701
|
}
|
702
|
|
703
|
public String getDbPrefix() {
|
704
|
return dbPrefix;
|
705
|
}
|
706
|
|
707
|
@Required
|
708
|
public void setDbPrefix(final String dbPrefix) {
|
709
|
this.dbPrefix = dbPrefix;
|
710
|
}
|
711
|
|
712
|
public DataSourceFactory getDataSourceFactory() {
|
713
|
return dataSourceFactory;
|
714
|
}
|
715
|
|
716
|
@Required
|
717
|
public void setDataSourceFactory(final DataSourceFactory dataSourceFactory) {
|
718
|
this.dataSourceFactory = dataSourceFactory;
|
719
|
}
|
720
|
|
721
|
public JdbcTemplateFactory getJdbcTemplateFactory() {
|
722
|
return jdbcTemplateFactory;
|
723
|
}
|
724
|
|
725
|
@Required
|
726
|
public void setJdbcTemplateFactory(final JdbcTemplateFactory jdbcTemplateFactory) {
|
727
|
this.jdbcTemplateFactory = jdbcTemplateFactory;
|
728
|
}
|
729
|
|
730
|
public TransactionTemplateFactory getTransactionTemplateFactory() {
|
731
|
return transactionTemplateFactory;
|
732
|
}
|
733
|
|
734
|
@Required
|
735
|
public void setTransactionTemplateFactory(final TransactionTemplateFactory transactionTemplateFactory) {
|
736
|
this.transactionTemplateFactory = transactionTemplateFactory;
|
737
|
}
|
738
|
|
739
|
public int getNumbersOfRecordsForTransaction() {
|
740
|
return numbersOfRecordsForTransaction;
|
741
|
}
|
742
|
|
743
|
@Required
|
744
|
public void setNumbersOfRecordsForTransaction(final int numbersOfRecordsForTransaction) {
|
745
|
this.numbersOfRecordsForTransaction = numbersOfRecordsForTransaction;
|
746
|
}
|
747
|
|
748
|
public String getDefaultDB() {
|
749
|
return defaultDB;
|
750
|
}
|
751
|
|
752
|
@Required
|
753
|
public void setDefaultDB(final String defaultDB) {
|
754
|
this.defaultDB = defaultDB;
|
755
|
}
|
756
|
|
757
|
public class TableDates {
|
758
|
|
759
|
private Date lastInsert;
|
760
|
private Date lastUpdate;
|
761
|
private Date lastDelete;
|
762
|
|
763
|
public Date getLastInsert() {
|
764
|
return lastInsert;
|
765
|
}
|
766
|
|
767
|
public void setLastInsert(final Date lastInsert) {
|
768
|
this.lastInsert = lastInsert;
|
769
|
}
|
770
|
|
771
|
public Date getLastUpdate() {
|
772
|
return lastUpdate;
|
773
|
}
|
774
|
|
775
|
public void setLastUpdate(final Date lastUpdate) {
|
776
|
this.lastUpdate = lastUpdate;
|
777
|
}
|
778
|
|
779
|
public Date getLastDelete() {
|
780
|
return lastDelete;
|
781
|
}
|
782
|
|
783
|
public void setLastDelete(final Date lastDelete) {
|
784
|
this.lastDelete = lastDelete;
|
785
|
}
|
786
|
}
|
787
|
|
788
|
}
|