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<String>();
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
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(dbName);
152
		try {
153
			if (clazz == Integer.class) return (T) jdbcTemplate.queryForObject(query, Integer.class);
154
			else if (clazz == List.class) return (T) jdbcTemplate.queryForList(query);
155
			else if (clazz == Map.class) return (T) jdbcTemplate.queryForMap(query);
156
			else if (clazz == SqlRowSet.class) return (T) jdbcTemplate.queryForRowSet(query);
157
			else if (clazz == BlockingQueue.class) {
158
				log.debug("Creating Queue");
159

    
160
				final ArrayBlockingQueue<Map<String, Object>> q = Queues.newArrayBlockingQueue(BLOCKING_QUEUE_SIZE);
161
				Executors.newSingleThreadExecutor().submit(() -> {
162
					try {
163
						final PreparedStatement stm = getStm(query, getConnection(jdbcTemplate));
164
						try (final ResultSet rs = stm.executeQuery()) {
165
							rs.setFetchSize(getFetchSize());
166
							while (rs.next()) {
167
								ResultSetMetaData md = rs.getMetaData();
168
								Map<String, Object> row = new HashMap<>();
169
								for (int i = 1; i <= md.getColumnCount(); i++) {
170
									row.put(md.getColumnName(i), rs.getObject(i));
171
								}
172
								if (!enqueue(q, row)) {
173
									break;
174
								}
175
							}
176
						} finally {
177
							getConnection(jdbcTemplate).setAutoCommit(true);
178
						}
179
						// An empty Map indicates the end of the resultset
180
						enqueue(q, new HashMap<>());
181
					} catch (SQLException e) {
182
						throw new RuntimeException(e);
183
					}
184
				});
185

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

    
188
				return (T) q;
189
			} else {
190
				jdbcTemplate.update(query);
191
				return null;
192
			}
193
		} catch (Throwable e) {
194
			throw new DatabaseException(e);
195
		}
196
	}
197

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

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

    
213
	private Connection getConnection(final JdbcTemplate jdbcTemplate) throws SQLException {
214
		final Connection conn = jdbcTemplate.getDataSource().getConnection();
215
		conn.setAutoCommit(false);
216
		return conn;
217
	}
218

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

    
231
	public List<Map<?, ?>> describeTable(final String database, final String table) throws DatabaseException {
232
		verifyParameters(database, table);
233

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

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

    
250
	public String dumpTableAsXML(final String db, final String t) throws DatabaseException {
251
		return dumpTableAsDoc(db, t).asXML();
252
	}
253

    
254
	public Document dumpTableAsDoc(final String db, final String t) throws DatabaseException {
255
		Document doc = DocumentHelper.createDocument();
256

    
257
		Element root = doc.addElement("DB_TABLE");
258
		Element head = root.addElement("HEADER");
259

    
260
		head.addElement("DATABASE").addAttribute("value", db);
261
		head.addElement("TABLE").addAttribute("value", t);
262
		head.addElement("DATE").addAttribute("value", DateUtils.now_ISO8601());
263

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

    
271
	public List<Document> dumpTableAsList(final String db, final String t) throws DatabaseException {
272
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(db);
273

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

    
283
	public Document rowToDocument(final Map<?, ?> map) throws DatabaseException {
284
		Document doc = DocumentHelper.createDocument();
285

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

    
295
	public Document getRowByResourceId(final String database, final String table, final String resourceId) throws DatabaseException {
296
		verifyParameters(database, table);
297

    
298
		JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
299
		String query = "SELECT * FROM " + table + " WHERE " + DNET_RESOURCE_ID_FIELD + "=?";
300

    
301
		Map<?, ?> map = jdbcTemplate.queryForMap(query, resourceId);
302
		Document doc = DocumentHelper.createDocument();
303

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

    
311
		Element body = root.addElement("BODY");
312

    
313
		Element row = body.addElement("ROW");
314

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

    
321
		return doc;
322
	}
323

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

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

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

    
353
	public void importFromIterable(final String db, final Iterable<String> iterable) throws DatabaseException {
354
		verifyParameters(db);
355

    
356
		final DataSource dataSource = dataSourceFactory.createDataSource(db);
357
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(db);
358
		final TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(dataSource);
359

    
360
		int counterTotal = 0;
361

    
362
		long start = DateUtils.now();
363

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

    
376
		long end = DateUtils.now();
377

    
378
		log.info("**********************************************************");
379
		log.info("Processed " + counterTotal + " rows in " + ((end - start) / 1000) + " seconds");
380
		log.info("**********************************************************");
381
	}
382

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

    
390
	private List<GenericRow> importTransactionInternal(final JdbcTemplate jdbcTemplate,
391
			final TransactionTemplate transactionTemplate,
392
			final List<GenericRow> rows) throws DatabaseException {
393

    
394
		final AtomicReference<DatabaseException> error = new AtomicReference<DatabaseException>();
395

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

    
422
	protected void addOrUpdateRow(final JdbcTemplate jdbcTemplate, final String table, final Map<String, Object> rowFields) throws DatabaseException {
423
		try {
424

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

    
431
			String fields = "";
432
			String values = "";
433
			List<Object> list = new ArrayList<Object>();
434

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

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

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

    
471
		List<Object> list = new ArrayList<Object>();
472

    
473
		String where = "";
474

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

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

    
486
		if (log.isDebugEnabled()) {
487
			log.debug("Number of Deleted records: " + n);
488
		}
489
	}
490

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

    
497
	public void clearTable(final String database, final String table) throws DatabaseException {
498
		verifyParameters(database, table);
499

    
500
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
501
		jdbcTemplate.update("DELETE FROM " + table);
502
	}
503

    
504
	public void prepareManagementOfTable(final String database, final String table) throws DatabaseException {
505
		verifyParameters(database, table);
506
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
507

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

    
514
	public void removeManagementOfTable(final String database, final String table) throws DatabaseException {
515
		verifyParameters(database, table);
516
		final JdbcTemplate jdbcTemplate = getJdbcTemplate(database);
517

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

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

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

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

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

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

    
555
	public void reassignDefaultDnetIdentifiers(final String db) throws DatabaseException {
556
		for (String t : listCommonDBTables(db)) {
557
			reassignDefaultDnetIdentifiers(db, t);
558
		}
559
	}
560

    
561
	public void reassignDefaultDnetIdentifiers(final String db, final String t) throws DatabaseException {
562
		if (!isManagedTable(db, t)) return;
563

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

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

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

    
585
		map.put("mainDB", defaultDB);
586
		map.put("db", db);
587
		map.put("table", table);
588
		map.put("idField", DNET_RESOURCE_ID_FIELD);
589

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

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

    
597
			List<GenericRow> list = new ArrayList<GenericRow>();
598

    
599
			for (Object or : doc.selectNodes("//ROW")) {
600
				Element row = (Element) or;
601

    
602
				String table = row.valueOf("@table");
603

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

    
606
				boolean toDelete = "deleted".equals(row.valueOf("@status"));
607

    
608
				Map<String, Object> fields = new HashMap<String, Object>();
609

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

    
617
					if ((key != null) && !key.isEmpty()) {
618
						Object value = valueS;
619
						if (type != null) {
620

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

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

    
656
	protected boolean parseBoolean(final String s) {
657
		if (TRUE_VALUES.contains(s.toLowerCase().trim())) return true;
658
		if (FALSE_VALUES.contains(s.toLowerCase().trim())) return false;
659

    
660
		return BooleanUtils.toBoolean(s);
661
	}
662

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

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

    
687
	private JdbcTemplate getJdbcTemplate(final String dbName) {
688
		JdbcTemplate jdbcTemplate = jdbcTemplateFactory.createJdbcTemplate(dbName);
689
		jdbcTemplate.setFetchSize(getFetchSize());
690
		return jdbcTemplate;
691
	}
692

    
693
	@Required
694
	public void setVelocityEngine(final VelocityEngine velocityEngine) {
695
		this.velocityEngine = velocityEngine;
696
	}
697

    
698
	public String getDbPrefix() {
699
		return dbPrefix;
700
	}
701

    
702
	@Required
703
	public void setDbPrefix(final String dbPrefix) {
704
		this.dbPrefix = dbPrefix;
705
	}
706

    
707
	public DataSourceFactory getDataSourceFactory() {
708
		return dataSourceFactory;
709
	}
710

    
711
	@Required
712
	public void setDataSourceFactory(final DataSourceFactory dataSourceFactory) {
713
		this.dataSourceFactory = dataSourceFactory;
714
	}
715

    
716
	public JdbcTemplateFactory getJdbcTemplateFactory() {
717
		return jdbcTemplateFactory;
718
	}
719

    
720
	@Required
721
	public void setJdbcTemplateFactory(final JdbcTemplateFactory jdbcTemplateFactory) {
722
		this.jdbcTemplateFactory = jdbcTemplateFactory;
723
	}
724

    
725
	public TransactionTemplateFactory getTransactionTemplateFactory() {
726
		return transactionTemplateFactory;
727
	}
728

    
729
	@Required
730
	public void setTransactionTemplateFactory(final TransactionTemplateFactory transactionTemplateFactory) {
731
		this.transactionTemplateFactory = transactionTemplateFactory;
732
	}
733

    
734
	public int getNumbersOfRecordsForTransaction() {
735
		return numbersOfRecordsForTransaction;
736
	}
737

    
738
	@Required
739
	public void setNumbersOfRecordsForTransaction(final int numbersOfRecordsForTransaction) {
740
		this.numbersOfRecordsForTransaction = numbersOfRecordsForTransaction;
741
	}
742

    
743
	public String getDefaultDB() {
744
		return defaultDB;
745
	}
746

    
747
	@Required
748
	public void setDefaultDB(final String defaultDB) {
749
		this.defaultDB = defaultDB;
750
	}
751

    
752
	public int getFetchSize() {
753
		return fetchSize;
754
	}
755

    
756
	public void setFetchSize(final int fetchSize) {
757
		this.fetchSize = fetchSize;
758
	}
759

    
760
	public class TableDates {
761

    
762
		private java.sql.Date lastInsert;
763
		private java.sql.Date lastUpdate;
764
		private java.sql.Date lastDelete;
765

    
766
		public java.sql.Date getLastInsert() {
767
			return lastInsert;
768
		}
769

    
770
		public void setLastInsert(final Date lastInsert) {
771
			this.lastInsert = lastInsert;
772
		}
773

    
774
		public Date getLastUpdate() {
775
			return lastUpdate;
776
		}
777

    
778
		public void setLastUpdate(final Date lastUpdate) {
779
			this.lastUpdate = lastUpdate;
780
		}
781

    
782
		public Date getLastDelete() {
783
			return lastDelete;
784
		}
785

    
786
		public void setLastDelete(final Date lastDelete) {
787
			this.lastDelete = lastDelete;
788
		}
789
	}
790

    
791
}
(1-1/3)