Project

General

Profile

1
package eu.dnetlib.enabling.datasources;
2

    
3
import java.io.StringWriter;
4
import java.util.*;
5
import java.util.stream.Collectors;
6

    
7
import com.google.common.collect.ImmutableMap;
8
import eu.dnetlib.enabling.datasources.DatasourceManagerClients.AfterSqlUpdate;
9
import eu.dnetlib.enabling.datasources.common.*;
10
import org.apache.commons.io.IOUtils;
11
import org.apache.commons.lang3.StringUtils;
12
import org.apache.commons.lang3.math.NumberUtils;
13
import org.apache.commons.logging.Log;
14
import org.apache.commons.logging.LogFactory;
15
import org.springframework.beans.factory.annotation.Required;
16
import org.springframework.core.io.ClassPathResource;
17
import org.springframework.core.io.Resource;
18
import org.springframework.transaction.annotation.Transactional;
19

    
20
public class LocalOpenaireDatasourceManagerImpl implements LocalOpenaireDatasourceManager {
21

    
22
	private DatasourceManagerClients datasourceManagerClients;
23

    
24
	private List<DbBrowsableField> browsableFields;
25

    
26
	public static final String QUERY_BASEDIR = "/eu/dnetlib/enabling/datasources/queries/";
27

    
28
	private static final Resource searchDsByType = new ClassPathResource(QUERY_BASEDIR + "searchDsByType.sql");
29
	private static final Resource searchApis = new ClassPathResource(QUERY_BASEDIR + "searchApisNormal.sql");
30
	private static final Resource searchApisUsingField = new ClassPathResource(QUERY_BASEDIR + "searchApisUsingField.sql");
31
	private static final Resource addDs = new ClassPathResource(QUERY_BASEDIR + "addDatasource.sql");
32
	private static final Resource addOrg = new ClassPathResource(QUERY_BASEDIR + "addOrganization.sql");
33
	private static final Resource deleteDs = new ClassPathResource(QUERY_BASEDIR + "deleteDatasource.sql");
34
	private static final Resource setActive = new ClassPathResource(QUERY_BASEDIR + "setActive.sql");
35
	private static final Resource setManaged = new ClassPathResource(QUERY_BASEDIR + "setManaged.sql");
36
	private static final Resource setCompliance = new ClassPathResource(QUERY_BASEDIR + "setCompliance.sql");
37
	private static final Resource overrideCompliance = new ClassPathResource(QUERY_BASEDIR + "overrideCompliance.sql");
38
	private static final Resource resetCompliance = new ClassPathResource(QUERY_BASEDIR + "resetCompliance.sql");
39
	private static final Resource setLastCollectionInfo = new ClassPathResource(QUERY_BASEDIR + "setLastCollectionInfo.sql");
40
	private static final Resource setLastAggregationInfo = new ClassPathResource(QUERY_BASEDIR + "setLastAggregationInfo.sql");
41
	private static final Resource setLastDownloadInfo = new ClassPathResource(QUERY_BASEDIR + "setLastDownloadInfo.sql");
42
	private static final Resource setLastValidationJob = new ClassPathResource(QUERY_BASEDIR + "setLastValidationJob.sql");
43
	private static final Resource resetLastOperationsInfo = new ClassPathResource(QUERY_BASEDIR + "resetLastOperationsInfo.sql");
44
	private static final Resource insertApiParam = new ClassPathResource(QUERY_BASEDIR + "insertApiParam.sql");
45
	private static final Resource insertApi = new ClassPathResource(QUERY_BASEDIR + "insertApi.sql");
46
	private static final Resource setRemovable = new ClassPathResource(QUERY_BASEDIR + "setRemovable.sql");
47

    
48
	private static final Log log = LogFactory.getLog(LocalOpenaireDatasourceManagerImpl.class);
49

    
50
	private static final String REPO_PROFILEID_SUFFIX = "_UmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZXMvUmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZVR5cGU=";
51

    
52
	@Override
53
	@Transactional(readOnly = true)
54
	public Set<String> listManagedDatasourceIds() throws DsmRuntimeException {
55
		try {
56
			return datasourceManagerClients.searchSQL("SELECT id FROM dsm_datasources WHERE managed = true", new HashMap<>())
57
					.stream()
58
					.map(m -> (String) m.get("id"))
59
					.collect(Collectors.toCollection(HashSet::new));
60
		} catch (final DsmException e) {
61
			throw new DsmRuntimeException(e);
62
		}
63
	}
64

    
65
	@Override
66
	@Transactional(readOnly = true)
67
	public List<SimpleDatasource> searchDatasourcesByType(final String type) throws DsmException {
68

    
69
		return datasourceManagerClients.searchSQL(searchDsByType, ImmutableMap.of("type", type))
70
				.stream()
71
				.map(DatasourceFunctions::mapToSimpleDs)
72
				.collect(Collectors.toList());
73
	}
74

    
75
	@Override
76
	@Transactional(readOnly = true)
77
	public List<? extends SearchApisEntry> searchApis(final String field, final Object value) throws DsmException {
78
		try {
79
			final StringWriter sql = new StringWriter();
80

    
81
			if (field.equalsIgnoreCase("__search__")) {
82
				sql.append(IOUtils.toString(searchApis.getInputStream()));
83
			} else {
84
				sql.append(IOUtils.toString(searchApisUsingField.getInputStream()));
85
				sql.append(field);
86
				sql.append("::text = ");
87
				sql.append(":value");
88
			}
89

    
90
			return datasourceManagerClients
91
					.searchSQL(sql.toString(), ImmutableMap.of("value", field.equalsIgnoreCase("__search__") ? "%" + value + "%" : value))
92
					.stream()
93
					.map(DatasourceFunctions::mapToSearchApisEntry)
94
					.collect(Collectors.toList());
95

    
96
		} catch (final Exception e) {
97
			log.error("Error searching field " + field + " - value: " + value, e);
98
		}
99
		return new ArrayList<>();
100
	}
101

    
102
	@Override
103
	@Transactional
104
	public void saveDs(final Datasource<Organization<?>, Identity> ds) throws DsmException {
105

    
106
		if (StringUtils.isBlank(ds.getAggregator())) {
107
			ds.setAggregator("OPENAIRE");
108
		}
109

    
110
		ds.setManaged(true);
111

    
112
		datasourceManagerClients.updateSQL(ds.getId(), addDs, AfterSqlUpdate.NONE, DatasourceFunctions.dsToMap(ds));
113

    
114
		if (ds.getOrganizations() != null) {
115
			for (final Organization<?> org : ds.getOrganizations()) {
116
				final Map<String, Object> orgParams = DatasourceFunctions.orgToMap(ds.getId(), org);
117
				datasourceManagerClients.updateSQL(ds.getId(), addOrg, AfterSqlUpdate.NONE, orgParams);
118
			}
119
		}
120
		final Map<String, Object> params = new HashMap<>();
121
		params.put("removable", true);
122
		params.put("dsId", ds.getId());
123
		datasourceManagerClients.updateSQL(ds.getId(), setRemovable, AfterSqlUpdate.NONE, params);
124

    
125
		datasourceManagerClients.regenerateProfile(ds.getId());
126
	}
127

    
128
	@Override
129
	@Transactional
130
	public void deleteDs(final String dsId) throws DsmException {
131
		datasourceManagerClients.updateSQL(fixDsId(dsId), deleteDs, AfterSqlUpdate.DELETE_DS_PROFILE, ImmutableMap.of("dsId", dsId));
132
	}
133

    
134
	@Override
135
	public Datasource<Organization<?>, Identity> getDs(final String dsId) throws DsmException {
136
		return datasourceManagerClients.getDatasourceById(fixDsId(dsId));
137
	}
138

    
139
	@Override
140
	public void regenerateProfiles() throws DsmException {
141
		datasourceManagerClients.regenerateProfiles();
142
	}
143

    
144
	@Override
145
	public List<Api<ApiParam>> getApis(final String dsId) throws DsmException {
146
		return datasourceManagerClients.getApis(fixDsId(dsId));
147
	}
148

    
149
	@Override
150
	public void setManaged(final String dsId, final boolean managed) throws DsmException {
151
		final String id = fixDsId(dsId);
152

    
153
		final Map<String, Object> params = new HashMap<>();
154
		params.put("managed", managed);
155
		params.put("dsId", id);
156

    
157
		datasourceManagerClients.updateSQL(id, setManaged, AfterSqlUpdate.NONE, params);
158

    
159
		params.clear();
160
		params.put("removable", true);
161
		params.put("dsId", id);
162

    
163
		datasourceManagerClients.updateSQL(id, setRemovable, AfterSqlUpdate.UPDATE_DS_PROFILE, params);
164

    
165
	}
166

    
167
	@Override
168
	public boolean isManaged(final String dsId) throws DsmException {
169
		final String q = "SELECT * from dsm_datasources WHERE id = :dsId AND managed = true";
170
		return !datasourceManagerClients.searchSQL(q, ImmutableMap.of("dsId", fixDsId(dsId))).isEmpty();
171
	}
172

    
173
	@Override
174
	@Transactional
175
	public void setActive(final String dsId, final String apiId, final boolean active) throws DsmException {
176
		final String id = fixDsId(dsId);
177

    
178
		final Map<String, Object> params = new HashMap<>();
179
		params.put("active", active);
180
		params.put("apiId", apiId);
181
		params.put("dsId", id);
182

    
183
		datasourceManagerClients.updateSQL(id, setActive, AfterSqlUpdate.NONE, params);
184
		if (!active) {
185
			datasourceManagerClients.updateSQL(dsId, resetLastOperationsInfo, AfterSqlUpdate.NONE, params);
186
		}
187

    
188
		setManaged(id, true); // It also update the IS profile
189
	}
190

    
191
	@Override
192
	@Transactional(readOnly = true)
193
	public boolean isActive(final String dsId, final String apiId) throws DsmException {
194
		final String q = "SELECT * from dsm_api WHERE id = :apiId AND datasource = :dsId AND active = true";
195
		return !datasourceManagerClients.searchSQL(q, ImmutableMap.of("dsId", fixDsId(dsId), "apiId", apiId)).isEmpty();
196
	}
197

    
198
	@Override
199
	@Transactional(readOnly = true)
200
	public boolean isRemovable(final String dsId, final String apiId) throws DsmException {
201
		final String q = "SELECT * from dsm_api WHERE id = :apiId AND datasource = :dsId AND active != true AND removable = true";
202
		return !datasourceManagerClients.searchSQL(q, ImmutableMap.of("dsId", fixDsId(dsId), "apiId", apiId)).isEmpty();
203
	}
204

    
205
	@Override
206
	@Transactional
207
	public void updateCompliance(final String dsId, final String apiId, final String level, final boolean override) throws DsmException {
208
		final String id = fixDsId(dsId);
209

    
210
		if (!override) {
211
			datasourceManagerClients.updateSQL(id, setCompliance, AfterSqlUpdate.NONE, ImmutableMap.of("level", level, "apiId", apiId, "dsId", id));
212
		} else if (level != null) {
213
			datasourceManagerClients.updateSQL(id, overrideCompliance, AfterSqlUpdate.NONE, ImmutableMap.of("level", level, "apiId", apiId, "dsId", id));
214
		} else {
215
			datasourceManagerClients.updateSQL(id, resetCompliance, AfterSqlUpdate.NONE, ImmutableMap.of("apiId", apiId, "dsId", id));
216
		}
217

    
218
		setManaged(id, true); // It also update the IS profile
219
	}
220

    
221
	@Override
222

    
223
	public void setLastCollectionInfo(final String dsId, final String apiId, final String mdId, final Integer size, final Date date)
224
			throws DsmException {
225
		setLastOperationInfo(setLastCollectionInfo, fixDsId(dsId), apiId, mdId, size, date);
226
	}
227

    
228
	@Override
229
	public void setLastAggregationInfo(final String dsId, final String apiId, final String mdId, final Integer size, final Date date)
230
			throws DsmException {
231
		setLastOperationInfo(setLastAggregationInfo, fixDsId(dsId), apiId, mdId, size, date);
232
	}
233

    
234
	@Override
235
	public void setLastDownloadInfo(final String dsId, final String apiId, final String objId, final Integer size, final Date date)
236
			throws DsmException {
237
		setLastOperationInfo(setLastDownloadInfo, fixDsId(dsId), apiId, objId, size, date);
238
	}
239

    
240
	@Override
241
	public void setLastValidationJob(String dsId, String apiId, String jobId) throws DsmException {
242
		final Map<String, Object> params = new HashMap<>();
243
		params.put("dsId", dsId);
244
		params.put("apiId", apiId);
245
		params.put("jobId", jobId);
246

    
247
		datasourceManagerClients.updateSQL(dsId, setLastValidationJob, AfterSqlUpdate.NONE, params);
248
		setManaged(dsId, true); // It also update the IS profile
249
	}
250

    
251
	@Transactional
252
	protected void setLastOperationInfo(final Resource sqlResource, final String dsId, final String apiId, final String mdId, final Integer size, final Date date)
253
			throws DsmException {
254
		final Map<String, Object> params = new HashMap<>();
255
		params.put("dsId", dsId);
256
		params.put("apiId", apiId);
257
		params.put("mdId", mdId);
258
		params.put("total", size);
259
		if (date != null) {
260
			params.put("date", new java.sql.Timestamp(date.getTime()));
261
		}
262

    
263
		datasourceManagerClients.updateSQL(dsId, sqlResource, AfterSqlUpdate.NONE, params);
264

    
265
		setManaged(dsId, true); // It also update the IS profile
266
	}
267

    
268
	@Override
269
	@Transactional
270
	public void updateApiDetails(final String dsId,
271
			final String apiId,
272
			final String metadataIdentifierPath,
273
			final String baseUrl,
274
			final Map<String, String> params)
275
			throws DsmException {
276

    
277
		final String id = fixDsId(dsId);
278

    
279
		// Delete old params
280
		datasourceManagerClients.updateSQL(id, "DELETE FROM dsm_apiparams WHERE api = :api", AfterSqlUpdate.NONE, ImmutableMap.of("api", apiId));
281

    
282
		// Insert new params
283
		for (final Map.Entry<String, String> e : params.entrySet()) {
284
			final Map<String, Object> sqlParams = ImmutableMap.of("param", e.getKey(), "value", e.getValue(), "api", apiId);
285
			datasourceManagerClients.updateSQL(id, insertApiParam, AfterSqlUpdate.NONE, sqlParams);
286
		}
287

    
288
		// Update the BaseURL
289
		datasourceManagerClients.updateSQL(id,
290
				"UPDATE dsm_api SET baseurl = :baseurl WHERE id = :api",
291
				AfterSqlUpdate.NONE,
292
				ImmutableMap.of("baseurl", baseUrl, "api", apiId));
293

    
294
		// Update the metadata_identifier_path
295
		datasourceManagerClients.updateSQL(id,
296
				"UPDATE dsm_api SET metadata_identifier_path = :path WHERE id = :api",
297
				AfterSqlUpdate.NONE,
298
				ImmutableMap.of("path", metadataIdentifierPath, "api", apiId));
299

    
300
		setManaged(id, true); // It also update the IS profile
301
	}
302

    
303
	@Override
304
	public List<? extends BrowsableField> listBrowsableFields() throws DsmException {
305
		return getBrowsableFields();
306
	}
307

    
308
	@Override
309
	public List<BrowseTerm> browseField(final String field) throws DsmException {
310
		final Optional<DbBrowsableField> bf = getBrowsableFields()
311
				.stream()
312
				.filter(f -> f.getId().equals(field))
313
				.findFirst();
314

    
315
		if (bf.isPresent()) {
316
			return datasourceManagerClients.searchSQL(bf.get().getSql(), new HashMap<>())
317
					.stream()
318
					.filter(m -> m.get("term") != null)
319
					.filter(m -> m.get("count") != null)
320
					.filter(m -> StringUtils.isNotBlank(m.get("term").toString()))
321
					.map(m -> new BrowseTermImpl(m.get("term").toString(), NumberUtils.toInt(m.get("count").toString(), 0)))
322
					.collect(Collectors.toList());
323
		} else {
324
			log.error("Not browsable field:" + field);
325
			throw new DsmException("Not browsable field:" + field);
326
		}
327
	}
328

    
329
	@Override
330
	@Transactional
331
	public void addApi(final Api<ApiParam> api) throws DsmException {
332

    
333
		datasourceManagerClients.updateSQL(api.getDatasource(), insertApi, AfterSqlUpdate.NONE, DatasourceFunctions.apiToMap(api));
334

    
335
		if (api.getApiParams() != null) {
336
			api.getApiParams().forEach(p -> {
337
				final ImmutableMap<String, Object> sqlParams = ImmutableMap.of("param", p.getParam(), "value", p.getValue(), "api", api.getId());
338
				try {
339
					datasourceManagerClients.updateSQL(api.getDatasource(), insertApiParam, AfterSqlUpdate.NONE, sqlParams);
340
				} catch (final DsmException e) {
341
					throw new RuntimeException(e);
342
				}
343
			});
344
		}
345

    
346
		setManaged(api.getDatasource(), true); // It also update the IS profile
347
	}
348

    
349
	@Override
350
	@Transactional
351
	public void deleteApi(final String dsId, final String apiId) throws DsmException {
352
		if (!isRemovable(dsId, apiId)) { throw new DsmException("The api " + apiId + " can't be deleted"); }
353

    
354
		datasourceManagerClients.updateSQL(dsId, "DELETE FROM dsm_apiparams WHERE api = :api", AfterSqlUpdate.NONE, ImmutableMap.of("api", apiId));
355
		datasourceManagerClients.updateSQL(dsId, "DELETE FROM dsm_api WHERE id = :api", AfterSqlUpdate.NONE, ImmutableMap.of("api", apiId));
356

    
357
		setManaged(dsId, true); // It also update the IS profile
358
	}
359

    
360
	public DatasourceManagerClients getDatasourceManagerClients() {
361
		return datasourceManagerClients;
362
	}
363

    
364
	private String fixDsId(final String dsId) throws DsmException {
365
		return dsId.endsWith(REPO_PROFILEID_SUFFIX) ? datasourceManagerClients.findDatasourceId(dsId) : dsId;
366
	}
367

    
368
	@Required
369
	public void setDatasourceManagerClients(final DatasourceManagerClients datasourceManagerClients) {
370
		this.datasourceManagerClients = datasourceManagerClients;
371
	}
372

    
373
	public List<DbBrowsableField> getBrowsableFields() {
374
		return browsableFields;
375
	}
376

    
377
	@Required
378
	public void setBrowsableFields(final List<DbBrowsableField> browsableFields) {
379
		this.browsableFields = browsableFields;
380
	}
381

    
382
}
(5-5/5)