Project

General

Profile

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.support.rowset.SqlRowSet;
41
import org.springframework.transaction.support.TransactionTemplate;
42
import org.springframework.ui.velocity.VelocityEngineUtils;
43

    
44
public class DatabaseUtils {
45

    
46
	public static final String DNET_RESOURCE_ID_FIELD = "_dnet_resource_identifier_";
47
	public static final int BLOCKING_QUEUE_TIMEOUT = 300;
48
	private static final String SQL_DATE_FORMAT = "yyyy-MM-dd";
49
	private static final Log log = LogFactory.getLog(DatabaseUtils.class); // NOPMD by marko on 11/24/08 5:02 PM
50
	private static final int BLOCKING_QUEUE_SIZE = 200;
51
	private static final Set<String> TRUE_VALUES = Sets.newHashSet("true", "t", "yes", "y", "vero", "v");
52
	private static final Set<String> FALSE_VALUES = Sets.newHashSet("false", "f", "no", "n", "falso");
53
	private DataSourceFactory dataSourceFactory;
54
	private JdbcTemplateFactory jdbcTemplateFactory;
55
	private TransactionTemplateFactory transactionTemplateFactory;
56
	private String defaultDB;
57
	private VelocityEngine velocityEngine;
58
	private String dbPrefix;
59
	private int numbersOfRecordsForTransaction;
60
	private int fetchSize = 100;
61

    
62
	public List<String> listCommonDBTables(final String database) throws DatabaseException {
63
		String query =
64
				"SELECT table_name FROM information_schema.tables " + "WHERE table_schema = 'public' " + "AND table_type != 'VIEW' "
65
						+ "AND table_name NOT LIKE '%_log'";
66
		return getTypedListFromSql(database, query, String.class);
67
	}
68

    
69
	public List<String> listCommonDBViews(final String database) throws DatabaseException {
70
		String query =
71
				"SELECT table_name FROM information_schema.tables " + "WHERE table_schema = 'public' " + "AND table_type = 'VIEW' "
72
						+ "AND table_name NOT LIKE '%_log'";
73
		return getTypedListFromSql(database, query, String.class);
74
	}
75

    
76
	public Map<String, TableDates> getTableDatesForDB(final String db) throws DatabaseException {
77
		Map<String, TableDates> res = new HashMap<String, TableDates>();
78

    
79
		for (String table : listCommonDBTables(db)) {
80
			try {
81
				TableDates dates = new TableDates();
82

    
83
				String query =
84
						"select lastinsert, lastupdate, lastdelete from " + "(select max(date) as lastinsert from " + table
85
								+ "_log where operation='insert') as t1, " + "(select max(date) as lastupdate from " + table
86
								+ "_log where operation='update') as t2, " + "(select max(date) as lastdelete from " + table
87
								+ "_log where operation='delete') as t3";
88

    
89
				SqlRowSet srs = executeSql(db, query, SqlRowSet.class);
90
				if (srs.next()) {
91
					dates.setLastInsert(srs.getDate("lastinsert"));
92
					dates.setLastUpdate(srs.getDate("lastupdate"));
93
					dates.setLastDelete(srs.getDate("lastdelete"));
94
				}
95
				res.put(table, dates);
96
			} catch (Exception e) {
97
				log.warn("Error obtaing dates for table " + table, e);
98
			}
99
		}
100
		return res;
101
	}
102

    
103
	public List<DnetDatabase> listAllDatabases() throws DatabaseException {
104
		final String query =
105
				"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 '"
106
						+ dbPrefix + "%' ORDER BY d.datname DESC";
107
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(defaultDB);
108

    
109
		final List<DnetDatabase> list = Lists.newArrayList();
110
		for (Map<String, Object> map : jdbcTemplate.queryForList(query)) {
111
			list.add(new DnetDatabase(map.get("db").toString(), Boolean.parseBoolean(map.get("managed").toString())));
112
		}
113
		return list;
114

    
115
	}
116

    
117
	public <T> List<T> getTypedListFromSql(final String dbName, final String query, final Class<T> clazz) throws DatabaseException {
118
		try {
119
			List<T> list = new ArrayList<T>();
120
			for (Object obj : getJdbcTemplate(dbName).queryForList(query, clazz)) {
121
				list.add(clazz.cast(obj));
122
			}
123
			return list;
124
		} catch (DataAccessException e) {
125
			throw new DatabaseException(e);
126
		}
127
	}
128

    
129
	public List<String> getSimpleListFromSql(final String dbName, final String query) throws DatabaseException {
130

    
131
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dbName);
132

    
133
		try {
134
			List<String> list = new ArrayList<>();
135
			for (Object obj : jdbcTemplate.queryForList(query)) {
136
				list.add(obj.toString());
137
			}
138
			return list;
139
		} catch (DataAccessException e) {
140
			throw new DatabaseException(e);
141
		}
142
	}
143

    
144
	public void executeSql(final String db, final String query) throws DatabaseException {
145
		executeSql(db, query, Void.class);
146
	}
147

    
148
	@SuppressWarnings("unchecked")
149
	public <T> T executeSql(final String dbName, final String query, final Class<T> clazz) throws DatabaseException {
150

    
151
		if (clazz == BlockingQueue.class) {
152
			log.debug("Creating Queue");
153

    
154
			final ArrayBlockingQueue<Map<String, Object>> queue = Queues.newArrayBlockingQueue(BLOCKING_QUEUE_SIZE);
155
			Executors.newSingleThreadExecutor().submit(() -> {
156

    
157
				try (final Connection con = getJdbcTemplate(dbName).getDataSource().getConnection();
158
						final PreparedStatement stm = getStm(query, con);
159
						final ResultSet rs = stm.executeQuery()) {
160
					con.setAutoCommit(false);
161
					rs.setFetchSize(getFetchSize());
162
					boolean timeout = false;
163
					while (rs.next()) {
164
						ResultSetMetaData md = rs.getMetaData();
165
						Map<String, Object> row = new HashMap<>();
166
						for (int i = 1; i <= md.getColumnCount(); i++) {
167
							row.put(md.getColumnName(i), rs.getObject(i));
168
						}
169
						if (!enqueue(queue, row)) {
170
							timeout = true;
171
							break;
172
						}
173
					}
174

    
175
					if (timeout) {
176
						throw new RuntimeException(String.format("queue full, consumer did not consume for %s seconds", BLOCKING_QUEUE_TIMEOUT));
177
					}
178
					// An empty Map indicates the end of the resultset
179
					enqueue(queue, new HashMap<>());
180
				} catch (SQLException e) {
181
					throw new RuntimeException(e);
182
				}
183
			});
184

    
185
			log.debug("Returned Queue");
186

    
187
			return (T) queue;
188
		}
189

    
190
		final JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
191
		if (clazz == Integer.class) return (T) jdbcTemplate.queryForObject(query, Integer.class);
192
		else if (clazz == List.class) return (T) jdbcTemplate.queryForList(query);
193
		else if (clazz == Map.class) return (T) jdbcTemplate.queryForMap(query);
194
		else if (clazz == SqlRowSet.class) return (T) jdbcTemplate.queryForRowSet(query);
195
		else {
196
			jdbcTemplate.update(query);
197
			return null;
198
		}
199
	}
200

    
201
	private boolean enqueue(final ArrayBlockingQueue<Map<String, Object>> q, final Map<String, Object> row) {
202
		try {
203
			return q.offer(row, BLOCKING_QUEUE_TIMEOUT, TimeUnit.SECONDS);
204
		} catch (InterruptedException e) {
205
			log.error("Error putting element in queue");
206
			throw new RuntimeException(e);
207
		}
208
	}
209

    
210
	private PreparedStatement getStm(final String query, final Connection con) throws SQLException {
211
		final PreparedStatement stm = con.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY);
212
		stm.setFetchSize(getFetchSize());
213
		return stm;
214
	}
215

    
216
	public boolean contains(final String db, final String table, final String column, final String value) throws DatabaseException {
217
		String query = "";
218
		try {
219
			verifyParameters(db, table, column);
220
			query = "SELECT " + column + " FROM " + table + " WHERE " + column + " = '" + value + "'";
221
			List<String> res = getSimpleListFromSql(db, query);
222
			return res != null && res.size() > 0;
223
		} catch (Throwable e) {
224
			throw new DatabaseException("Error performing SQL: " + query, e);
225
		}
226
	}
227

    
228
	public List<Map<?, ?>> describeTable(final String database, final String table) throws DatabaseException {
229
		verifyParameters(database, table);
230

    
231
		try {
232
			final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
233
			List<Map<?, ?>> response = new ArrayList<Map<?, ?>>();
234
			String query = "SELECT * FROM information_schema.columns WHERE table_name = ?";
235

    
236
			for (Object o : jdbcTemplate.queryForList(query, new Object[] { table })) {
237
				if (o instanceof Map<?, ?>) {
238
					response.add((Map<?, ?>) o);
239
				}
240
			}
241
			return response;
242
		} catch (DataAccessException e) {
243
			throw new DatabaseException(e);
244
		}
245
	}
246

    
247
	public String dumpTableAsXML(final String db, final String t) throws DatabaseException {
248
		return dumpTableAsDoc(db, t).asXML();
249
	}
250

    
251
	public Document dumpTableAsDoc(final String db, final String t) throws DatabaseException {
252
		Document doc = DocumentHelper.createDocument();
253

    
254
		Element root = doc.addElement("DB_TABLE");
255
		Element head = root.addElement("HEADER");
256

    
257
		head.addElement("DATABASE").addAttribute("value", db);
258
		head.addElement("TABLE").addAttribute("value", t);
259
		head.addElement("DATE").addAttribute("value", DateUtils.now_ISO8601());
260

    
261
		Element body = root.addElement("BODY");
262
		for (Document d : dumpTableAsList(db, t)) {
263
			body.add(d.getRootElement());
264
		}
265
		return doc;
266
	}
267

    
268
	public List<Document> dumpTableAsList(final String db, final String t) throws DatabaseException {
269
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(db);
270

    
271
		List<Document> list = new ArrayList<Document>();
272
		for (Object o : jdbcTemplate.queryForList("SELECT * FROM " + t)) {
273
			if (o instanceof Map<?, ?>) {
274
				list.add(rowToDocument((Map<?, ?>) o));
275
			}
276
		}
277
		return list;
278
	}
279

    
280
	public Document rowToDocument(final Map<?, ?> map) throws DatabaseException {
281
		Document doc = DocumentHelper.createDocument();
282

    
283
		Element row = doc.addElement("ROW");
284
		for (Map.Entry<?, ?> entry : map.entrySet()) {
285
			Element col = row.addElement("FIELD");
286
			col.addAttribute("name", "" + entry.getKey());
287
			addValue(col, entry.getValue());
288
		}
289
		return doc;
290
	}
291

    
292
	public Document getRowByResourceId(final String database, final String table, final String resourceId) throws DatabaseException {
293
		verifyParameters(database, table);
294

    
295
		JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
296
		String query = "SELECT * FROM " + table + " WHERE " + DNET_RESOURCE_ID_FIELD + "=?";
297

    
298
		Map<?, ?> map = jdbcTemplate.queryForMap(query, resourceId);
299
		Document doc = DocumentHelper.createDocument();
300

    
301
		Element root = doc.addElement("DB_RECORD");
302
		Element head = root.addElement("HEADER");
303
		head.addElement("RESOURCE_IDENTIFIER").addAttribute("value", resourceId);
304
		head.addElement("DATABASE").addAttribute("value", database);
305
		head.addElement("TABLE").addAttribute("value", table);
306
		head.addElement("DATE").addAttribute("value", DateUtils.now_ISO8601());
307

    
308
		Element body = root.addElement("BODY");
309

    
310
		Element row = body.addElement("ROW");
311

    
312
		for (Map.Entry<?, ?> entry : map.entrySet()) {
313
			Element col = row.addElement("FIELD");
314
			col.addAttribute("name", "" + entry.getKey());
315
			addValue(col, entry.getValue());
316
		}
317

    
318
		return doc;
319
	}
320

    
321
	private void addValue(final Element elem, final Object value) throws DatabaseException {
322
		if (value instanceof Array) {
323
			try {
324
				for (Object o : (Object[]) ((Array) value).getArray()) {
325
					addValue(elem.addElement("ITEM"), o);
326
				}
327
			} catch (Exception e) {
328
				throw new DatabaseException("Error procsessing a Array", e);
329
			}
330
		} else if (value != null) {
331
			elem.addText(Sanitizer.sanitize(value.toString()));
332
		} else {
333
			elem.addAttribute("isNull", "true");
334
		}
335
	}
336

    
337
	private void verifyParameters(final String... params) throws DatabaseException {
338
		Pattern pattern = Pattern.compile("\\w{1,128}");
339

    
340
		for (String p : params) {
341
			log.debug("TESTING SQL PARAM:" + p);
342
			if (p == null) throw new DatabaseException("Parameter is null");
343
			else if (!pattern.matcher(p).matches()) throw new DatabaseException("Parameter [" + p + "] contains an invalid character");
344
			else {
345
				log.debug("TEST OK");
346
			}
347
		}
348
	}
349

    
350
	public void importFromIterable(final String db, final Iterable<String> iterable) throws DatabaseException {
351
		verifyParameters(db);
352

    
353
		final DataSource dataSource = dataSourceFactory.createDataSource(db);
354
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(db);
355
		final TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(dataSource);
356

    
357
		int counterTotal = 0;
358

    
359
		long start = DateUtils.now();
360

    
361
		List<GenericRow> rows = new ArrayList<GenericRow>();
362
		for (String prof : iterable) {
363
			rows.addAll(obtainListOfRows(prof));
364
			if (rows.size() > numbersOfRecordsForTransaction) {
365
				counterTotal += rows.size();
366
				importTransaction(jdbcTemplate, transactionTemplate, rows);
367
				rows.clear();
368
			}
369
		}
370
		counterTotal += rows.size();
371
		importTransaction(jdbcTemplate, transactionTemplate, rows);
372

    
373
		long end = DateUtils.now();
374

    
375
		log.info("**********************************************************");
376
		log.info("Processed " + counterTotal + " rows in " + ((end - start) / 1000) + " seconds");
377
		log.info("**********************************************************");
378
	}
379

    
380
	private void importTransaction(final JdbcTemplate jdbcTemplate, final TransactionTemplate transactionTemplate, List<GenericRow> rows)
381
			throws DatabaseException {
382
		if (rows != null && rows.size() > 0) {
383
			importTransactionInternal(jdbcTemplate, transactionTemplate, rows);
384
		}
385
	}
386

    
387
	private List<GenericRow> importTransactionInternal(final JdbcTemplate jdbcTemplate,
388
			final TransactionTemplate transactionTemplate,
389
			final List<GenericRow> rows) throws DatabaseException {
390

    
391
		final AtomicReference<DatabaseException> error = new AtomicReference<DatabaseException>();
392

    
393
		try {
394
			return transactionTemplate.execute(status -> {
395
				final List<GenericRow> ok = Lists.newArrayList();
396
				try {
397
					for (GenericRow row : rows) {
398
						if (row.isToDelete()) {
399
							deleteRow(jdbcTemplate, row.getTable(), row.getFields());
400
						} else {
401
							addOrUpdateRow(jdbcTemplate, row.getTable(), row.getFields());
402
						}
403
						ok.add(row);
404
					}
405
				} catch (DatabaseException e) {
406
					log.warn("Transaction failed", e);
407
					status.setRollbackOnly();
408
					error.set(e);
409
				}
410
				return ok;
411
			});
412
		} finally {
413
			if (error.get() != null) {
414
				throw error.get();
415
			}
416
		}
417
	}
418

    
419
	protected void addOrUpdateRow(final JdbcTemplate jdbcTemplate, final String table, final Map<String, Object> rowFields) throws DatabaseException {
420
		try {
421

    
422
			if (log.isDebugEnabled()) {
423
				log.debug("Adding or updating element to table " + table);
424
			}
425
			verifyParameters(table);
426
			verifyParameters(rowFields.keySet().toArray(new String[rowFields.size()]));
427

    
428
			String fields = "";
429
			String values = "";
430
			List<Object> list = new ArrayList<Object>();
431

    
432
			for (Map.Entry<String, Object> e : rowFields.entrySet()) {
433
				if (!fields.isEmpty()) {
434
					fields += ",";
435
				}
436
				fields += e.getKey();
437
				if (!values.isEmpty()) {
438
					values += ",";
439
				}
440
				values += "?";
441
				list.add(e.getValue());
442
			}
443

    
444
			int count = 0;
445
			if (rowFields.containsKey(DNET_RESOURCE_ID_FIELD)) {
446
				List<Object> list2 = new ArrayList<Object>();
447
				list2.addAll(list);
448
				list2.add(rowFields.get(DNET_RESOURCE_ID_FIELD));
449
				count =
450
						jdbcTemplate.update("UPDATE " + table + " SET (" + fields + ") = (" + values + ") WHERE " + DNET_RESOURCE_ID_FIELD + "=?",
451
								list2.toArray());
452
			}
453
			if (count == 0) {
454
				jdbcTemplate.update("INSERT INTO " + table + " (" + fields + ") VALUES (" + values + ")", list.toArray());
455
			}
456
		} catch (final Exception e) {
457
			throw new DatabaseException("Error adding or updating record", e);
458
		}
459
	}
460

    
461
	protected void deleteRow(final JdbcTemplate jdbcTemplate, final String table, final Map<String, Object> rowFields) throws DatabaseException {
462
		if (log.isDebugEnabled()) {
463
			log.debug("Deleting element from table " + table);
464
		}
465
		verifyParameters(table);
466
		verifyParameters(rowFields.keySet().toArray(new String[rowFields.size()]));
467

    
468
		List<Object> list = new ArrayList<Object>();
469

    
470
		String where = "";
471

    
472
		for (Map.Entry<String, Object> e : rowFields.entrySet()) {
473
			if (!where.isEmpty()) {
474
				where += " AND ";
475
			}
476
			where += e.getKey() + "=?";
477
			list.add(e.getValue());
478
		}
479

    
480
		if (where.isEmpty()) throw new DatabaseException("Delete condition is empty");
481
		int n = jdbcTemplate.update("DELETE FROM " + table + " WHERE " + where, list.toArray());
482

    
483
		if (log.isDebugEnabled()) {
484
			log.debug("Number of Deleted records: " + n);
485
		}
486
	}
487

    
488
	public void deleteRowByResourceId(final String database, final String table, final String resourceIdentifier) throws DatabaseException {
489
		verifyParameters(database, table, resourceIdentifier);
490
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
491
		jdbcTemplate.update("DELETE FROM " + table + " WHERE " + DNET_RESOURCE_ID_FIELD + "=?", resourceIdentifier);
492
	}
493

    
494
	public void clearTable(final String database, final String table) throws DatabaseException {
495
		verifyParameters(database, table);
496

    
497
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
498
		jdbcTemplate.update("DELETE FROM " + table);
499
	}
500

    
501
	public void prepareManagementOfTable(final String database, final String table) throws DatabaseException {
502
		verifyParameters(database, table);
503
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
504

    
505
		if (!isManagedTable(jdbcTemplate, table)) {
506
			jdbcTemplate.update(getSQLFromTemplate("manageTable", database, table, null));
507
			log.info("Added management of table " + table);
508
		}
509
	}
510

    
511
	public void removeManagementOfTable(final String database, final String table) throws DatabaseException {
512
		verifyParameters(database, table);
513
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
514

    
515
		if (isManagedTable(jdbcTemplate, table)) {
516
			jdbcTemplate.update(getSQLFromTemplate("unmanageTable", database, table, null));
517
			log.info("Removed management of table " + table);
518
		}
519
	}
520

    
521
	public boolean isManagedTable(final String database, final String table) throws DatabaseException {
522
		verifyParameters(database, table);
523
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
524
		return isManagedTable(jdbcTemplate, table);
525
	}
526

    
527
	private boolean isManagedTable(final JdbcTemplate jdbcTemplate, final String table) {
528
		return jdbcTemplate.queryForObject("SELECT count(*) FROM information_schema.columns WHERE table_name = ? AND column_name = ?", Integer.class,
529
				table, DNET_RESOURCE_ID_FIELD) == 1;
530
	}
531

    
532
	public boolean isLoggedTable(final String database, final String table) throws DatabaseException {
533
		verifyParameters(database, table);
534
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
535
		return isLoggedTable(jdbcTemplate, table);
536
	}
537

    
538
	private boolean isLoggedTable(final JdbcTemplate jdbcTemplate, final String table) {
539
		return jdbcTemplate.queryForObject("SELECT count(*) FROM information_schema.tables WHERE table_name = ?", Integer.class,
540
				table + "_log") == 1;
541
	}
542

    
543
	public String getDefaultDnetIdentifier(final String database, final String table) throws DatabaseException {
544
		verifyParameters(database, table);
545
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
546
		if (isManagedTable(jdbcTemplate, table)) return jdbcTemplate.queryForObject(
547
				"SELECT column_default FROM information_schema.columns WHERE table_name = ? AND column_name = ?", new Object[] {
548
						table, DNET_RESOURCE_ID_FIELD }, String.class);
549
		return "";
550
	}
551

    
552
	public void reassignDefaultDnetIdentifiers(final String db) throws DatabaseException {
553
		for (String t : listCommonDBTables(db)) {
554
			reassignDefaultDnetIdentifiers(db, t);
555
		}
556
	}
557

    
558
	public void reassignDefaultDnetIdentifiers(final String db, final String t) throws DatabaseException {
559
		if (!isManagedTable(db, t)) return;
560

    
561
		SqlRowSet rows =
562
				executeSql(db, "SELECT pg_attribute.attname as pkey FROM pg_index, pg_class, pg_attribute " + "WHERE pg_class.oid = '" + t + "'::regclass "
563
						+ "AND indrelid = pg_class.oid " + "AND pg_attribute.attrelid = pg_class.oid "
564
						+ "AND pg_attribute.attnum = any(pg_index.indkey) AND indisprimary " + "ORDER BY pkey", SqlRowSet.class);
565

    
566
		String defaultValue = "";
567
		while (rows.next()) {
568
			if (!defaultValue.isEmpty()) {
569
				defaultValue += "||'@@'||";
570
			}
571
			defaultValue += rows.getString("pkey");
572
		}
573
		executeSql(db, "UPDATE " + t + " SET " + DatabaseUtils.DNET_RESOURCE_ID_FIELD + " = " + defaultValue);
574
		log.info("Reassigned dnetId for table " + t);
575
	}
576

    
577
	public String getSQLFromTemplate(final String sqlTemplate, final String db, final String table, Map<String, Object> map) {
578
		if (map == null) {
579
			map = new HashMap<String, Object>();
580
		}
581

    
582
		map.put("mainDB", defaultDB);
583
		map.put("db", db);
584
		map.put("table", table);
585
		map.put("idField", DNET_RESOURCE_ID_FIELD);
586

    
587
		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "eu/dnetlib/enabling/database/velocity/" + sqlTemplate + ".sql.vm", "UTF-8", map);
588
	}
589

    
590
	public List<GenericRow> obtainListOfRows(final String xml) throws DatabaseException {
591
		try {
592
			Document doc = new SAXReader().read(new StringReader(xml));
593

    
594
			List<GenericRow> list = new ArrayList<GenericRow>();
595

    
596
			for (Object or : doc.selectNodes("//ROW")) {
597
				Element row = (Element) or;
598

    
599
				String table = row.valueOf("@table");
600

    
601
				if ((table == null) || table.isEmpty()) throw new DatabaseException("Attribute table is missing in XSLT");
602

    
603
				boolean toDelete = "deleted".equals(row.valueOf("@status"));
604

    
605
				Map<String, Object> fields = new HashMap<String, Object>();
606

    
607
				for (Object of : row.selectNodes("./FIELD")) {
608
					Node node = (Node) of;
609
					String key = node.valueOf("@name");
610
					String type = node.valueOf("@type");
611
					String format = node.valueOf("@format");
612
					String valueS = node.getText().trim();
613

    
614
					if ((key != null) && !key.isEmpty()) {
615
						Object value = valueS;
616
						if (type != null) {
617

    
618
							try {
619
								// probably an empty string in a typed field means null
620
								if ("".equals(valueS)) {
621
									value = null;
622
								} else if (type.equals("int")) {
623
									value = Integer.parseInt(valueS);
624
								} else if (type.equals("float")) {
625
									value = Float.parseFloat(valueS);
626
								} else if (type.equals("boolean")) {
627
									value = parseBoolean(valueS);
628
								} else if (type.equals("date")) {
629
									value = parseDate(valueS, format);
630
								} else if (type.equals("iso8601Date")) {
631
									DateTime date = ISODateTimeFormat.dateTimeParser().parseDateTime(valueS);
632
									value = date.toDate();
633
									// value = new DateUtils().parse(valueS);
634
								}
635
							} catch (IllegalArgumentException e) {
636
								log.fatal("cannot convert '" + valueS + "' to " + type, e);
637
								throw e;
638
							}
639
						}
640
						fields.put(key, value);
641
					}
642
				}
643

    
644
				list.add(new GenericRow(table, fields, toDelete));
645
			}
646
			return list;
647
		} catch (Exception e) {
648
			log.error("Error obtaining list of rows from xml: " + xml);
649
			throw new DatabaseException(e);
650
		}
651
	}
652

    
653
	protected boolean parseBoolean(final String s) {
654
		if (TRUE_VALUES.contains(s.toLowerCase().trim())) return true;
655
		if (FALSE_VALUES.contains(s.toLowerCase().trim())) return false;
656

    
657
		return BooleanUtils.toBoolean(s);
658
	}
659

    
660
	public void setManaged(final String dbName, final boolean managed) throws DatabaseException {
661
		verifyParameters(dbName);
662
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dbName);
663
		if (managed) {
664
			jdbcTemplate.update("COMMENT ON DATABASE " + dbName + " IS 'isManaged'");
665
		} else {
666
			jdbcTemplate.update("COMMENT ON DATABASE " + dbName + " IS NULL");
667
		}
668
	}
669

    
670
	// public for testing
671
	public Date parseDate(final String date, String format) {
672
		if ((format == null) || format.isEmpty()) {
673
			format = SQL_DATE_FORMAT;
674
		}
675
		try {
676
			java.util.Date parsed = new SimpleDateFormat(format).parse(date);
677
			String ret = new SimpleDateFormat(SQL_DATE_FORMAT).format(parsed);
678
			return Date.valueOf(ret);
679
		} catch (ParseException e) {
680
			return null;
681
		}
682
	}
683

    
684
	private JdbcTemplate getJdbcTemplate(final String dbName) {
685
		JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
686
		jdbcTemplate.setFetchSize(getFetchSize());
687
		return jdbcTemplate;
688
	}
689

    
690
	@Required
691
	public void setVelocityEngine(final VelocityEngine velocityEngine) {
692
		this.velocityEngine = velocityEngine;
693
	}
694

    
695
	public String getDbPrefix() {
696
		return dbPrefix;
697
	}
698

    
699
	@Required
700
	public void setDbPrefix(final String dbPrefix) {
701
		this.dbPrefix = dbPrefix;
702
	}
703

    
704
	public DataSourceFactory getDataSourceFactory() {
705
		return dataSourceFactory;
706
	}
707

    
708
	@Required
709
	public void setDataSourceFactory(final DataSourceFactory dataSourceFactory) {
710
		this.dataSourceFactory = dataSourceFactory;
711
	}
712

    
713
	public JdbcTemplateFactory getJdbcTemplateFactory() {
714
		return jdbcTemplateFactory;
715
	}
716

    
717
	@Required
718
	public void setJdbcTemplateFactory(final JdbcTemplateFactory jdbcTemplateFactory) {
719
		this.jdbcTemplateFactory = jdbcTemplateFactory;
720
	}
721

    
722
	public TransactionTemplateFactory getTransactionTemplateFactory() {
723
		return transactionTemplateFactory;
724
	}
725

    
726
	@Required
727
	public void setTransactionTemplateFactory(final TransactionTemplateFactory transactionTemplateFactory) {
728
		this.transactionTemplateFactory = transactionTemplateFactory;
729
	}
730

    
731
	public int getNumbersOfRecordsForTransaction() {
732
		return numbersOfRecordsForTransaction;
733
	}
734

    
735
	@Required
736
	public void setNumbersOfRecordsForTransaction(final int numbersOfRecordsForTransaction) {
737
		this.numbersOfRecordsForTransaction = numbersOfRecordsForTransaction;
738
	}
739

    
740
	public String getDefaultDB() {
741
		return defaultDB;
742
	}
743

    
744
	@Required
745
	public void setDefaultDB(final String defaultDB) {
746
		this.defaultDB = defaultDB;
747
	}
748

    
749
	public int getFetchSize() {
750
		return fetchSize;
751
	}
752

    
753
	public void setFetchSize(final int fetchSize) {
754
		this.fetchSize = fetchSize;
755
	}
756

    
757
	public class TableDates {
758

    
759
		private java.sql.Date lastInsert;
760
		private java.sql.Date lastUpdate;
761
		private java.sql.Date lastDelete;
762

    
763
		public java.sql.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
}
(1-1/3)