Project

General

Profile

« Previous | Next » 

Revision 45190

codebase used to migrate to java8 the production system

View differences:

modules/dnet-datasource-manager-service/trunk/deploy.info
1
{"type_source": "SVN", "goal": "package -U -T 4C source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-datasource-manager-service/trunk/", "deploy_repository": "dnet4-snapshots", "version": "4", "mail": "sandro.labruzzo@isti.cnr.it,michele.artini@isti.cnr.it, claudio.atzori@isti.cnr.it, alessia.bardi@isti.cnr.it", "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet4-snapshots", "name": "dnet-datasource-manager-service"}
modules/dnet-datasource-manager-service/trunk/src/main/java/eu/dnetlib/enabling/datasources/IfaceDescToNode.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import java.util.Map.Entry;
4

  
5
import org.dom4j.DocumentHelper;
6
import org.dom4j.Element;
7

  
8
import eu.dnetlib.enabling.datasources.rmi.IfaceDesc;
9

  
10
public class IfaceDescToNode {
11

  
12
	public static Element convert(final IfaceDesc iface) throws Exception {
13

  
14
		final Element ifcNode = DocumentHelper.createElement("INTERFACE");
15
		ifcNode.addAttribute("id", iface.getId());
16
		ifcNode.addAttribute("label", iface.getTypology() + " (" + iface.getCompliance() + ")");
17
		ifcNode.addAttribute("compliance", iface.getCompliance());
18
		ifcNode.addAttribute("typology", iface.getTypology());
19
		ifcNode.addAttribute("contentDescription", iface.getContentDescription());
20
		ifcNode.addAttribute("active", Boolean.toString(iface.getActive()));
21
		ifcNode.addAttribute("removable", Boolean.toString(iface.getRemovable()));
22

  
23
		final Element acProtoNode = ifcNode.addElement("ACCESS_PROTOCOL");
24

  
25
		for (Entry<String, String> e : iface.getAccessParams().entrySet()) {
26
			acProtoNode.addAttribute(e.getKey(), e.getValue());
27
		}
28
		acProtoNode.setText(iface.getAccessProtocol());
29

  
30
		ifcNode.addElement("BASE_URL").setText(iface.getBaseUrl());
31

  
32
		for (Entry<String, String> e : iface.getExtraFields().entrySet()) {
33
			final Element field = ifcNode.addElement("INTERFACE_EXTRA_FIELD");
34
			field.addAttribute("name", e.getKey());
35
			field.setText(e.getValue());
36
		}
37

  
38
		return ifcNode;
39
	}
40
}
modules/dnet-datasource-manager-service/trunk/src/main/java/eu/dnetlib/enabling/datasources/XmlBrowsableField.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import eu.dnetlib.enabling.datasources.rmi.BrowsableField;
4

  
5
public class XmlBrowsableField extends BrowsableField {
6

  
7
	private String xpath;
8
	private String vocabulary;
9

  
10
	public XmlBrowsableField() {
11
		super();
12
	}
13

  
14
	public XmlBrowsableField(final String id, final String label) {
15
		super(id, label);
16
	}
17

  
18
	public XmlBrowsableField(final String id, final String label, final String xpath, final String vocabulary) {
19
		super(id, label);
20
		this.xpath = xpath;
21
		this.vocabulary = vocabulary;
22
	}
23

  
24
	public String getXpath() {
25
		return xpath;
26
	}
27

  
28
	public void setXpath(final String xpath) {
29
		this.xpath = xpath;
30
	}
31

  
32
	public String getVocabulary() {
33
		return vocabulary;
34
	}
35

  
36
	public void setVocabulary(final String vocabulary) {
37
		this.vocabulary = vocabulary;
38
	}
39

  
40
}
modules/dnet-datasource-manager-service/trunk/src/main/java/eu/dnetlib/enabling/datasources/DatasourceManagerServiceImpl.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import java.io.StringReader;
4
import java.text.ParseException;
5
import java.util.Collections;
6
import java.util.Date;
7
import java.util.List;
8
import java.util.Map;
9

  
10
import javax.annotation.Resource;
11

  
12
import org.antlr.stringtemplate.StringTemplate;
13
import org.apache.commons.io.IOUtils;
14
import org.apache.commons.lang.StringEscapeUtils;
15
import org.apache.commons.lang.StringUtils;
16
import org.apache.commons.lang.math.NumberUtils;
17
import org.apache.commons.logging.Log;
18
import org.apache.commons.logging.LogFactory;
19
import org.dom4j.Document;
20
import org.dom4j.Element;
21
import org.dom4j.Node;
22
import org.dom4j.io.SAXReader;
23
import org.quartz.CronExpression;
24
import org.springframework.beans.factory.annotation.Required;
25
import org.springframework.core.io.ClassPathResource;
26

  
27
import com.google.common.base.Function;
28
import com.google.common.collect.Lists;
29
import com.google.common.collect.Maps;
30
import com.google.common.collect.Sets;
31

  
32
import eu.dnetlib.enabling.datasources.rmi.BrowsableField;
33
import eu.dnetlib.enabling.datasources.rmi.BrowseTerm;
34
import eu.dnetlib.enabling.datasources.rmi.DatasourceConstants;
35
import eu.dnetlib.enabling.datasources.rmi.DatasourceDesc;
36
import eu.dnetlib.enabling.datasources.rmi.DatasourceManagerService;
37
import eu.dnetlib.enabling.datasources.rmi.DatasourceManagerServiceException;
38
import eu.dnetlib.enabling.datasources.rmi.IfaceDesc;
39
import eu.dnetlib.enabling.datasources.rmi.RepositoryMapEntry;
40
import eu.dnetlib.enabling.datasources.rmi.SearchInterfacesEntry;
41
import eu.dnetlib.enabling.datasources.rmi.SimpleDatasourceDesc;
42
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
43
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
44
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
45
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryException;
46
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
47
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
48
import eu.dnetlib.enabling.tools.AbstractBaseService;
49

  
50
public class DatasourceManagerServiceImpl extends AbstractBaseService implements DatasourceManagerService {
51

  
52
	private static final Log log = LogFactory.getLog(DatasourceManagerServiceImpl.class);
53

  
54
	private static final String REPOSITORY_RESOURCE_TYPE = "RepositoryServiceResourceType";
55

  
56
	private List<XmlBrowsableField> browsableFields;
57

  
58
	private ClassPathResource findReposQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/findRepos.xquery.st");
59

  
60
	private ClassPathResource browseRepoApisQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/browseRepoApis.xquery.st");
61
	private ClassPathResource findRepoApisQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/findRepoApis.xquery.st");
62
	private ClassPathResource findReposMapQuery = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/findReposMap.xquery");
63
	private ClassPathResource simpleFindReposQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/simpleFindRepos.xquery.st");
64

  
65
	@Resource
66
	private UniqueServiceLocator serviceLocator;
67

  
68
	private String environment;
69

  
70
	private String fixDsId(final String dsId) throws DatasourceManagerServiceException {
71
		if (dsId.endsWith("_UGVuZGluZ1JlcG9zaXRvcnlSZXNvdXJjZXMvUmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZVR5cGU=")
72
				|| dsId.endsWith("_UmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZXMvUmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZVR5cGU=")) {
73
			return dsId;
74
		} else {
75
			try {
76
				return serviceLocator
77
						.getService(ISLookUpService.class)
78
						.getResourceProfileByQuery(
79
								"for $x in collection("
80
										+ "'/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType',"
81
										+ "'/db/DRIVER/PendingRepositoryResources/RepositoryServiceResourceType') "
82
										+ "where $x//DATASOURCE_ORIGINAL_ID = '" + dsId + "' "
83
										+ "return $x//RESOURCE_IDENTIFIER/@value/string()");
84
			} catch (Exception e) {
85
				throw new DatasourceManagerServiceException("Invalid id: " + dsId, e);
86
			}
87
		}
88
	}
89

  
90
	@Override
91
	public boolean addDatasource(final DatasourceDesc ds) throws DatasourceManagerServiceException {
92
		try {
93
			final String profile = DatasourceDescToProfile.convert(ds, environment);
94
			serviceLocator.getService(ISRegistryService.class).registerProfile(profile);
95
			return true;
96
		} catch (Exception e) {
97
			log.error("Error registering profile", e);
98
			throw new DatasourceManagerServiceException("Error registering profile", e);
99
		}
100
	}
101

  
102
	@Override
103
	public boolean deleteDatasource(final String dsId) throws DatasourceManagerServiceException {
104
		return _deleteDatasource(fixDsId(dsId));
105
	}
106

  
107
	private boolean _deleteDatasource(final String dsId) throws DatasourceManagerServiceException {
108
		try {
109
			return serviceLocator.getService(ISRegistryService.class).deleteProfile(dsId);
110
		} catch (ISRegistryException e) {
111
			log.error("Error deleting profile " + dsId, e);
112
			throw new DatasourceManagerServiceException("Error deleting profile " + dsId, e);
113
		}
114
	}
115

  
116
	@Override
117
	public DatasourceDesc getDatasource(final String dsId) throws DatasourceManagerServiceException {
118
		return _getDatasource(fixDsId(dsId));
119
	}
120

  
121
	private DatasourceDesc _getDatasource(final String dsId) throws DatasourceManagerServiceException {
122
		try {
123
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
124
			return ProfileToDatasourceDesc.convert(profile);
125
		} catch (Exception e) {
126
			log.error("Error accessing profile " + dsId, e);
127
			throw new DatasourceManagerServiceException("Error accessing profile " + dsId, e);
128
		}
129
	}
130

  
131
	@Override
132
	public List<DatasourceDesc> listAllDatasources() throws DatasourceManagerServiceException {
133
		return listDatasourcesUsingFilter(null, null, null, null);
134
	}
135

  
136
	@Override
137
	public List<DatasourceDesc> listDatasourcesUsingFilter(final String compliance,
138
			final String contentDescription,
139
			final String iisProcessingWorkflow,
140
			final String collectedFrom)
141
			throws DatasourceManagerServiceException {
142
		try {
143
			final StringTemplate st = new StringTemplate();
144
			st.setTemplate(IOUtils.toString(findReposQueryTmpl.getInputStream()));
145

  
146
			final Map<String, String> conds = Maps.newHashMap();
147

  
148
			if (StringUtils.isNotBlank(compliance)) {
149
				conds.put("//INTERFACE/@compliance", compliance);
150
			}
151
			if (StringUtils.isNotBlank(contentDescription)) {
152
				conds.put("//INTERFACE/@contentDescription", contentDescription);
153
			}
154
			if (StringUtils.isNotBlank(iisProcessingWorkflow)) {
155
				// NOT USED
156
			}
157
			if (StringUtils.isNotBlank(collectedFrom)) {
158
				// NOT USED
159
			}
160

  
161
			if (!conds.isEmpty()) {
162
				st.setAttribute("conds", conds);
163
			}
164

  
165
			final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(st.toString());
166

  
167
			return Lists.transform(list, new ProfileToDatasourceDesc());
168
		} catch (Exception e) {
169
			log.error("Error listing datasources", e);
170
			throw new DatasourceManagerServiceException("Error listing datasources", e);
171
		}
172
	}
173

  
174
	@Override
175
	public boolean updateLevelOfCompliance(final String dsId, final String ifaceId, final String level) throws DatasourceManagerServiceException {
176
		return _updateLevelOfCompliance(fixDsId(dsId), ifaceId, level);
177
	}
178

  
179
	private boolean _updateLevelOfCompliance(final String dsId, final String ifaceId, final String level) throws DatasourceManagerServiceException {
180
		try {
181
			return serviceLocator.getService(ISRegistryService.class)
182
					.updateProfileNode(dsId, "//INTERFACE[@id = '" + ifaceId + "']/@compliance", "'" + level + "'");
183
		} catch (Exception e) {
184
			log.error("Error updating profile: " + dsId, e);
185
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
186
		}
187
	}
188

  
189
	@Override
190
	public boolean updateBaseUrl(final String dsId, final String ifaceId, final String baseUrl) throws DatasourceManagerServiceException {
191
		return _updateBaseUrl(fixDsId(dsId), ifaceId, baseUrl);
192
	}
193

  
194
	private boolean _updateBaseUrl(final String dsId, final String ifaceId, final String baseUrl) throws DatasourceManagerServiceException {
195
		try {
196
			return serviceLocator.getService(ISRegistryService.class)
197
					.updateProfileNode(dsId, "//INTERFACE[@id = '" + ifaceId + "']/BASE_URL", "<BASE_URL>" + baseUrl + "</BASE_URL>");
198
		} catch (Exception e) {
199
			log.error("Error updating profile: " + dsId, e);
200
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
201
		}
202
	}
203

  
204
	@Override
205
	public boolean updateActivationStatus(final String dsId, final String ifaceId, final boolean active) throws DatasourceManagerServiceException {
206
		return _updateActivationStatus(fixDsId(dsId), ifaceId, active);
207
	}
208

  
209
	private boolean _updateActivationStatus(final String dsId, final String ifaceId, final boolean active) throws DatasourceManagerServiceException {
210
		try {
211
			return serviceLocator.getService(ISRegistryService.class)
212
					.updateProfileNode(dsId, "//INTERFACE[@id = '" + ifaceId + "']/@active", "'" + active + "'");
213
		} catch (Exception e) {
214
			log.error("Error updating profile: " + dsId, e);
215
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
216
		}
217
	}
218

  
219
	@Override
220
	public boolean updateContentDescription(final String dsId, final String ifaceId, final String desc) throws DatasourceManagerServiceException {
221
		return _updateContentDescription(fixDsId(dsId), ifaceId, desc);
222
	}
223

  
224
	private boolean _updateContentDescription(final String dsId, final String ifaceId, final String desc) throws DatasourceManagerServiceException {
225
		try {
226
			return serviceLocator.getService(ISRegistryService.class)
227
					.updateProfileNode(dsId, "//INTERFACE[@id = '" + ifaceId + "']/@contentDescription", "'" + desc + "'");
228
		} catch (Exception e) {
229
			log.error("Error updating profile: " + dsId, e);
230
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
231
		}
232
	}
233

  
234
	@Override
235
	public boolean setIisProcessingWorkflow(final String dsId, final String ifaceId, final String wf) throws DatasourceManagerServiceException {
236
		throw new DatasourceManagerServiceException("NOT IMPLEMENTED");
237
	}
238

  
239
	@Override
240
	public boolean updateExtraField(final String dsId, final String ifaceId, final String field, final String value, final boolean preserveOriginal)
241
			throws DatasourceManagerServiceException {
242
		return _updateExtraField(fixDsId(dsId), ifaceId, field, value, preserveOriginal);
243
	}
244

  
245
	private boolean _updateExtraField(final String dsId, final String ifaceId, final String field, final String value, final boolean preserveOriginal)
246
			throws DatasourceManagerServiceException {
247
		try {
248
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
249
			final Document doc = new SAXReader().read(new StringReader(profile));
250

  
251
			final Node ifcNode = doc.selectSingleNode("//INTERFACE[@id = '" + ifaceId + "']");
252
			final Node node = ifcNode.selectSingleNode("./INTERFACE_EXTRA_FIELD[@name = '" + field + "']");
253
			if (node != null) {
254
				node.setText(value);
255
			} else {
256
				final Element e = ((Element) ifcNode).addElement("INTERFACE_EXTRA_FIELD");
257
				e.addAttribute("name", field);
258
				e.setText(value);
259
			}
260
			return serviceLocator.getService(ISRegistryService.class).updateProfile(dsId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
261
		} catch (Exception e) {
262
			log.error("Error updating profile: " + dsId, e);
263
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
264
		}
265
	}
266

  
267
	@Override
268
	public boolean updateAccessParam(final String dsId, final String ifaceId, final String field, final String value, final boolean preserveOriginal)
269
			throws DatasourceManagerServiceException {
270
		return _updateAccessParam(fixDsId(dsId), ifaceId, field, value, preserveOriginal);
271
	}
272

  
273
	private boolean _updateAccessParam(final String dsId, final String ifaceId, final String field, final String value, final boolean preserveOriginal)
274
			throws DatasourceManagerServiceException {
275
		try {
276
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
277
			final Document doc = new SAXReader().read(new StringReader(profile));
278

  
279
			final Node node = doc.selectSingleNode("//INTERFACE[@id = '" + ifaceId + "']/ACCESS_PROTOCOL");
280
			((Element) node).addAttribute(field, value);
281

  
282
			return serviceLocator.getService(ISRegistryService.class).updateProfile(dsId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
283
		} catch (Exception e) {
284
			log.error("Error updating profile: " + dsId, e);
285
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
286
		}
287
	}
288

  
289
	@Override
290
	public boolean deleteAccessParamOrExtraField(final String dsId, final String ifaceId, final String field) throws DatasourceManagerServiceException {
291
		return _deleteAccessParamOrExtraField(fixDsId(dsId), ifaceId, field);
292
	}
293

  
294
	private boolean _deleteAccessParamOrExtraField(final String dsId, final String ifaceId, final String field) throws DatasourceManagerServiceException {
295
		try {
296
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
297
			final Document doc = new SAXReader().read(new StringReader(profile));
298

  
299
			final Node ef = doc.selectSingleNode("//INTERFACE[@id = '" + ifaceId + "']/INTERFACE_EXTRA_FIELD[@name = '" + field + "']");
300
			if (ef != null) {
301
				ef.detach();
302
			}
303
			final Node ap = doc.selectSingleNode("//INTERFACE[@id = '" + ifaceId + "']/ACCESS_PROTOCOL/@" + field);
304
			if (ap != null) {
305
				ap.detach();
306

  
307
			}
308
			return serviceLocator.getService(ISRegistryService.class).updateProfile(dsId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
309
		} catch (Exception e) {
310
			log.error("Error updating profile: " + dsId, e);
311
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
312
		}
313
	}
314

  
315
	@Override
316
	public boolean addInterface(final String dsId, final IfaceDesc iface) throws DatasourceManagerServiceException {
317
		iface.setRemovable(true);
318
		return _addInterface(fixDsId(dsId), iface);
319
	}
320

  
321
	private boolean _addInterface(final String dsId, final IfaceDesc iface) throws DatasourceManagerServiceException {
322
		try {
323
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
324
			final Document doc = new SAXReader().read(new StringReader(profile));
325

  
326
			final Node node = doc.selectSingleNode("//INTERFACE[@id = '" + iface.getId() + "']");
327
			if (node != null) {
328
				node.detach();
329
			}
330

  
331
			((Element) doc.selectSingleNode("//INTERFACES")).add(IfaceDescToNode.convert(iface));
332

  
333
			return serviceLocator.getService(ISRegistryService.class).updateProfile(dsId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
334
		} catch (Exception e) {
335
			log.error("Error updating profile: " + dsId, e);
336
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
337
		}
338
	}
339

  
340
	@Override
341
	public boolean deleteInterface(final String dsId, final String ifaceId) throws DatasourceManagerServiceException {
342
		return _deleteInterface(fixDsId(dsId), ifaceId);
343
	}
344

  
345
	private boolean _deleteInterface(final String dsId, final String ifaceId) throws DatasourceManagerServiceException {
346
		try {
347
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
348
			final Document doc = new SAXReader().read(new StringReader(profile));
349

  
350
			final Node node = doc.selectSingleNode("//INTERFACE[@id = '" + ifaceId + "']");
351
			if (node != null) {
352
				node.detach();
353
			}
354

  
355
			return serviceLocator.getService(ISRegistryService.class).updateProfile(dsId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
356
		} catch (Exception e) {
357
			log.error("Error updating profile: " + dsId, e);
358
			throw new DatasourceManagerServiceException("Error updating profile: " + dsId, e);
359
		}
360
	}
361

  
362
	@Override
363
	public boolean updateSQL(final String dsId, final String sql, final boolean delete) throws DatasourceManagerServiceException {
364
		throw new DatasourceManagerServiceException("NOT IMPLEMENTED");
365
	}
366

  
367
	@Override
368
	public Date findNextScheduledExecution(final String dsId, final String ifaceId) throws DatasourceManagerServiceException {
369
		return _findNextScheduledExecution(fixDsId(dsId), ifaceId);
370
	}
371

  
372
	private Date _findNextScheduledExecution(final String dsId, final String ifaceId) throws DatasourceManagerServiceException {
373
		final String xquery = "/*[.//DATAPROVIDER/@interface='" + ifaceId + "' and .//SCHEDULING/@enabled='true']//CRON/text()";
374
		try {
375
			final String cronExpression = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(xquery);
376
			final CronExpression cron = new CronExpression(cronExpression);
377
			return cron.getNextValidTimeAfter(new Date());
378
		} catch (ISLookUpDocumentNotFoundException e) {
379
			// When the value is not found a null value must be returned
380
			return null;
381
		} catch (ISLookUpException e) {
382
			log.error("Error in xquery: " + xquery, e);
383
			throw new DatasourceManagerServiceException("Error in xquery: " + xquery, e);
384
		} catch (ParseException e) {
385
			log.error("Error parsing cron expression", e);
386
			throw new DatasourceManagerServiceException("Error parsing cron expression", e);
387
		}
388
	}
389

  
390
	@Override
391
	public boolean bulkUpdateApiExtraFields(final String repoId, final String ifaceId, final Map<String, String> fields)
392
			throws DatasourceManagerServiceException {
393
		try {
394
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(repoId);
395

  
396
			final SAXReader reader = new SAXReader();
397
			final Document doc = reader.read(new StringReader(profile));
398

  
399
			final Element iface = (Element) doc.selectSingleNode("//INTERFACE[@id='" + ifaceId + "']");
400
			if (iface != null) {
401

  
402
				while (iface.selectNodes("./INTERFACE_EXTRA_FIELD").size() > 0) {
403
					iface.selectSingleNode("./INTERFACE_EXTRA_FIELD").detach();
404
				}
405
				for (Map.Entry<String, String> e : fields.entrySet()) {
406
					if (e.getValue() != null && !e.getValue().isEmpty()) {
407
						final Element field = iface.addElement("INTERFACE_EXTRA_FIELD");
408
						field.addAttribute("name", e.getKey());
409
						field.addText(e.getValue());
410
					}
411
				}
412
				serviceLocator.getService(ISRegistryService.class).updateProfile(repoId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
413
			} else {
414
				log.error("Invalid interface: " + ifaceId);
415
				throw new DatasourceManagerServiceException("Missing interface: " + ifaceId);
416
			}
417
		} catch (Exception e) {
418
			log.error("Error updating API of profile: " + repoId);
419
			throw new DatasourceManagerServiceException("Error updating API of profile: " + repoId, e);
420
		}
421
		return true;
422

  
423
	}
424

  
425
	@Override
426
	public boolean bulkUpdateApiAccessParams(final String dsId, final String ifaceId, final Map<String, String> params)
427
			throws DatasourceManagerServiceException {
428
		return _bulkUpdateApiAccessParams(fixDsId(dsId), ifaceId, params);
429
	}
430

  
431
	private boolean _bulkUpdateApiAccessParams(final String repoId, final String ifaceId, final Map<String, String> params)
432
			throws DatasourceManagerServiceException {
433
		try {
434
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(repoId);
435

  
436
			final SAXReader reader = new SAXReader();
437
			final Document doc = reader.read(new StringReader(profile));
438

  
439
			final Element accessNode = (Element) doc.selectSingleNode("//INTERFACE[@id='" + ifaceId + "']/ACCESS_PROTOCOL");
440
			if (accessNode != null) {
441
				while (accessNode.attributes().size() > 0) {
442
					accessNode.selectSingleNode("@*").detach();
443
				}
444
				for (Map.Entry<String, String> e : params.entrySet()) {
445
					if (e.getValue() != null && !e.getValue().isEmpty()) {
446
						if (e.getKey().equalsIgnoreCase("baseUrl")) {
447
							doc.selectSingleNode("//INTERFACE[@id='" + ifaceId + "']/BASE_URL").setText(e.getValue());
448
						} else {
449
							accessNode.addAttribute(e.getKey(), e.getValue());
450
						}
451
					}
452
				}
453
				serviceLocator.getService(ISRegistryService.class).updateProfile(repoId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
454
			} else {
455
				log.error("Invalid interface: " + ifaceId);
456
				throw new DatasourceManagerServiceException("Missing interface: " + ifaceId);
457
			}
458
		} catch (Exception e) {
459
			log.error("Error updating API of profile: " + repoId);
460
			throw new DatasourceManagerServiceException("Error updating API of profile: " + repoId, e);
461
		}
462
		return true;
463
	}
464

  
465
	@Override
466
	public boolean overrideCompliance(final String dsId, final String ifaceId, final String level) throws DatasourceManagerServiceException {
467
		return _overrideCompliance(fixDsId(dsId), ifaceId, level);
468
	}
469

  
470
	private boolean _overrideCompliance(final String repoId, final String ifaceId, final String compliance) throws DatasourceManagerServiceException {
471
		try {
472
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(repoId);
473

  
474
			final SAXReader reader = new SAXReader();
475
			final Document doc = reader.read(new StringReader(profile));
476

  
477
			final Element iface = (Element) doc.selectSingleNode("//INTERFACE[@id='" + ifaceId + "']");
478
			if (iface != null) {
479
				final Map<String, String> fields = Maps.newHashMap();
480

  
481
				if (!StringUtils.isEmpty(compliance)) {
482
					fields.put(DatasourceConstants.OVERRIDING_COMPLIANCE_FIELD, compliance);
483
				}
484

  
485
				while (iface.selectNodes("./INTERFACE_EXTRA_FIELD").size() > 0) {
486
					final Node node = iface.selectSingleNode("./INTERFACE_EXTRA_FIELD");
487
					final String name = node.valueOf("@name");
488

  
489
					if (!name.equals(DatasourceConstants.OVERRIDING_COMPLIANCE_FIELD)) {
490
						fields.put(node.valueOf("@name"), node.getText());
491
					}
492
					node.detach();
493
				}
494

  
495
				for (Map.Entry<String, String> e : fields.entrySet()) {
496
					if (e.getValue() != null && !e.getValue().isEmpty()) {
497
						final Element field = iface.addElement("INTERFACE_EXTRA_FIELD");
498
						field.addAttribute("name", e.getKey());
499
						field.addText(e.getValue());
500
					}
501
				}
502
				serviceLocator.getService(ISRegistryService.class).updateProfile(repoId, doc.asXML(), REPOSITORY_RESOURCE_TYPE);
503
			} else {
504
				log.error("Invalid interface: " + ifaceId);
505
				throw new DatasourceManagerServiceException("Missing interface: " + ifaceId);
506
			}
507
		} catch (Exception e) {
508
			log.error("Error updating API of profile: " + repoId);
509
			throw new DatasourceManagerServiceException("Error updating API of profile: " + repoId, e);
510
		}
511

  
512
		return true;
513
	}
514

  
515
	@Override
516
	public List<BrowsableField> listBrowsableFields() throws DatasourceManagerServiceException {
517
		return Lists.transform(getBrowsableFields(), new Function<XmlBrowsableField, BrowsableField>() {
518

  
519
			@Override
520
			public BrowsableField apply(final XmlBrowsableField f) {
521
				return new BrowsableField(f.getId(), f.getLabel());
522
			}
523
		});
524
	}
525

  
526
	@Override
527
	public List<BrowseTerm> browseField(final String f) throws DatasourceManagerServiceException {
528

  
529
		final List<BrowseTerm> list = Lists.newArrayList();
530

  
531
		try {
532
			final XmlBrowsableField field = findBrowseField(f);
533
			if (field != null) {
534
				final StringTemplate st = new StringTemplate(IOUtils.toString(browseRepoApisQueryTmpl.getInputStream()));
535
				st.setAttribute("xpath", field.getXpath());
536

  
537
				final Map<String, String> terms = fetchVocabularyTerms(field.getVocabulary());
538

  
539
				for (String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(st.toString())) {
540
					final String[] arr = s.split("@-@-@");
541
					final String id = arr[0].trim();
542
					final int count = NumberUtils.toInt(arr[1].trim(), 0);
543
					list.add(new BrowseTerm(id, findLabel(id, terms), count));
544
				}
545
			}
546
		} catch (Exception e) {
547
			log.error("Error browsing field " + f, e);
548
		}
549

  
550
		return list;
551
	}
552

  
553
	private String findLabel(final String code, final Map<String, String> terms) {
554
		return terms.containsKey(code) ? terms.get(code) : code;
555
	}
556

  
557
	public Map<String, String> fetchVocabularyTerms(final String voc) throws ISLookUpException {
558
		final String xquery = "for $x in collection('/db/DRIVER/VocabularyDSResources/VocabularyDSResourceType')[.//VOCABULARY_NAME/@code = '"
559
				+ voc.trim() + "']//TERM return concat($x/@code, ' @@@ ', $x/@english_name)";
560

  
561
		final Map<String, String> map = Maps.newHashMap();
562
		for (String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(xquery)) {
563
			final String[] arr = s.split("@@@");
564
			map.put(arr[0].trim(), arr[1].trim());
565
		}
566
		return map;
567
	}
568

  
569
	private XmlBrowsableField findBrowseField(final String id) {
570
		for (XmlBrowsableField f : getBrowsableFields()) {
571
			if (f.getId().equals(id)) { return f; }
572
		}
573
		return null;
574
	}
575

  
576
	@Override
577
	public List<SearchInterfacesEntry> searchInterface(final String field, final String value) throws DatasourceManagerServiceException {
578
		try {
579

  
580
			final StringTemplate st = new StringTemplate();
581
			st.setTemplate(IOUtils.toString(findRepoApisQueryTmpl.getInputStream()));
582

  
583
			if (field.equalsIgnoreCase("__search__")) {
584
				st.setAttribute("cond", "contains(../..//(*|@*)/lower-case(.), '" + StringEscapeUtils.escapeXml(value.toLowerCase()) + "')");
585
			} else {
586
				final XmlBrowsableField f = findBrowseField(field);
587
				if (f != null) {
588
					st.setAttribute("cond", f.getXpath() + "='" + StringEscapeUtils.escapeXml(value) + "'");
589
				} else {
590
					return Lists.newArrayList();
591
				}
592
			}
593

  
594
			final String query = st.toString();
595

  
596
			final SAXReader reader = new SAXReader();
597

  
598
			final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(query);
599

  
600
			return Lists.transform(list, new Function<String, SearchInterfacesEntry>() {
601

  
602
				@Override
603
				public SearchInterfacesEntry apply(final String s) {
604
					final SearchInterfacesEntry iface = new SearchInterfacesEntry();
605
					try {
606
						final Document doc = reader.read(new StringReader(s));
607
						final String country = doc.valueOf("//REPO/@country");
608

  
609
						iface.setRepoId(doc.valueOf("//REPO/@id"));
610
						iface.setRepoCountry(StringUtils.isEmpty(country) ? "-" : country.toUpperCase());
611
						iface.setRepoName(doc.valueOf("//REPO/@name"));
612
						iface.setRepoPrefix(doc.valueOf("//REPO/@prefix"));
613

  
614
						final Node ifcNode = doc.selectSingleNode("//INTERFACE");
615

  
616
						iface.setId(ifcNode.valueOf("./@id"));
617
						iface.setActive(Boolean.valueOf(ifcNode.valueOf("./@active")));
618
						iface.setProtocol(ifcNode.valueOf("./ACCESS_PROTOCOL/text()"));
619

  
620
						final String overCompliance = ifcNode.valueOf("./INTERFACE_EXTRA_FIELD[@name='overriding_compliance']");
621
						if (StringUtils.isEmpty(overCompliance)) {
622
							iface.setCompliance(ifcNode.valueOf("@compliance"));
623
						} else {
624
							iface.setCompliance(overCompliance);
625
						}
626

  
627
						final String lastAggregationDate = ifcNode.valueOf("./INTERFACE_EXTRA_FIELD[@name='last_aggregation_date']");
628
						if (!StringUtils.isEmpty(lastAggregationDate)) {
629
							iface.setAggrDate(lastAggregationDate);
630
						} else {
631
							final String lastDownloadDate = ifcNode.valueOf("./INTERFACE_EXTRA_FIELD[@name='last_download_date']");
632
							if (!StringUtils.isEmpty(lastDownloadDate)) {
633
								iface.setAggrDate(lastDownloadDate);
634
							}
635
						}
636
						final String lastAggregationTotal = ifcNode.valueOf("./INTERFACE_EXTRA_FIELD[@name='last_aggregation_total']");
637
						if (StringUtils.isEmpty(lastAggregationTotal)) {
638
							final String lastDownloadTotal = ifcNode.valueOf("./INTERFACE_EXTRA_FIELD[@name='last_download_total']");
639
							if (StringUtils.isEmpty(lastDownloadTotal)) {
640
								iface.setAggrTotal(0);
641
							} else {
642
								iface.setAggrTotal(NumberUtils.toInt(lastDownloadTotal, 0));
643
							}
644
						} else {
645
							iface.setAggrTotal(NumberUtils.toInt(lastAggregationTotal, 0));
646
						}
647
					} catch (Exception e) {
648
						log.error(e);
649
					}
650
					return iface;
651
				}
652
			});
653
		} catch (Exception e) {
654
			log.error("Error searching field " + field + " - value: " + value, e);
655
		}
656
		return Lists.newArrayList();
657
	}
658

  
659
	@Override
660
	public List<RepositoryMapEntry> getRepositoryMap() throws DatasourceManagerServiceException {
661
		try {
662
			final SAXReader reader = new SAXReader();
663

  
664
			final String query = IOUtils.toString(findReposMapQuery.getInputStream());
665
			final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(query);
666
			return Lists.transform(list, new Function<String, RepositoryMapEntry>() {
667

  
668
				@Override
669
				public RepositoryMapEntry apply(final String s) {
670
					final RepositoryMapEntry r = new RepositoryMapEntry();
671

  
672
					try {
673
						final Document doc = reader.read(new StringReader(s));
674
						r.setId(doc.valueOf("//dsId"));
675
						r.setName(doc.valueOf("//name"));
676
						r.setLat(Float.parseFloat(doc.valueOf("//lat")));
677
						r.setLng(Float.parseFloat(doc.valueOf("//lng")));
678
					} catch (Exception e) {
679
						log.error(e);
680
					}
681
					return r;
682
				}
683
			});
684
		} catch (Exception e) {
685
			log.error("Error obtaing repo map entries", e);
686
		}
687
		return Lists.newArrayList();
688
	}
689

  
690
	private List<XmlBrowsableField> getBrowsableFields() {
691
		return browsableFields;
692
	}
693

  
694
	@Required
695
	public void setBrowsableFields(final List<XmlBrowsableField> browsableFields) {
696
		this.browsableFields = browsableFields;
697
	}
698

  
699
	@Override
700
	public List<SimpleDatasourceDesc> simpleListDatasourcesByType(final String type) throws DatasourceManagerServiceException {
701
		try {
702
			final List<SimpleDatasourceDesc> list = Lists.newArrayList();
703

  
704
			final StringTemplate st = new StringTemplate(IOUtils.toString(simpleFindReposQueryTmpl.getInputStream()));
705
			st.setAttribute("type", type);
706

  
707
			for (String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(st.toString())) {
708
				final SimpleDatasourceDesc r = new SimpleDatasourceDesc();
709
				final String[] arr = s.split("@=@");
710
				r.setId(arr[0].trim());
711
				r.setName(arr[1].trim());
712
				r.setOrigId(arr[2].trim());
713
				r.setApis(Sets.newHashSet(arr[3].replaceAll("\\s", "").split(",")));
714
				r.setValid("true".equals(arr[4].trim()));
715
				r.setTypology(type);
716
				list.add(r);
717
			}
718

  
719
			Collections.sort(list);
720

  
721
			return list;
722
		} catch (Exception e) {
723
			log.error("Error listing repos", e);
724
		}
725
		return Lists.newArrayList();
726
	}
727

  
728
	public String getEnvironment() {
729
		return environment;
730
	}
731

  
732
	@Required
733
	public void setEnvironment(final String environment) {
734
		this.environment = environment;
735
	}
736

  
737
}
modules/dnet-datasource-manager-service/trunk/src/main/java/eu/dnetlib/enabling/datasources/DatasourceDescToProfile.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import com.google.common.base.Function;
4
import eu.dnetlib.enabling.datasources.rmi.DatasourceDesc;
5
import eu.dnetlib.enabling.datasources.rmi.IfaceDesc;
6
import eu.dnetlib.miscutils.datetime.DateUtils;
7
import org.apache.commons.lang.StringUtils;
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
10
import org.dom4j.DocumentHelper;
11
import org.dom4j.Element;
12

  
13
public class DatasourceDescToProfile implements Function<DatasourceDesc, String> {
14
	private static final Log log = LogFactory.getLog(DatasourceDescToProfile.class);
15

  
16
	public DatasourceDescToProfile(final String environment) {
17
		this.environment = environment;
18
	}
19

  
20
	private String environment;
21

  
22
	public static String convert(final DatasourceDesc ds, String environment) throws Exception {
23
		final Element root = DocumentHelper.createElement("RESOURCE_PROFILE");
24

  
25
		final Element header = root.addElement("HEADER");
26
		header.addElement("RESOURCE_IDENTIFIER").addAttribute("value", "");
27
		header.addElement("RESOURCE_TYPE").addAttribute("value", "RepositoryServiceResourceType");
28
		header.addElement("RESOURCE_KIND").addAttribute("value", "RepositoryServiceResources");
29
		header.addElement("RESOURCE_URI").addAttribute("value", "");
30
		header.addElement("DATE_OF_CREATION").addAttribute("value", DateUtils.now_ISO8601());
31
		header.addElement("PROTOCOL");
32

  
33
		final Element body = root.addElement("BODY");
34
		final Element conf = body.addElement("CONFIGURATION");
35
		conf.addElement("DATASOURCE_TYPE").setText(ds.getDatasourceClass());
36

  
37
		final Element origId = conf.addElement("DATASOURCE_ORIGINAL_ID");
38
		origId.addAttribute("provenance", "D-NET");
39
		origId.setText(ds.getId());
40

  
41
		conf.addElement("DATASOURCE_AGGREGATED").setText("false");
42
		conf.addElement("ENVIRONMENTS").addElement("ENVIRONMENT").setText(environment);
43
		conf.addElement("TYPOLOGY").setText(""+ds.getTypology());
44
		conf.addElement("MAX_SIZE_OF_DATASTRUCTURE").setText("0");
45
		conf.addElement("AVAILABLE_DISKSPACE").setText("0");
46
		conf.addElement("MAX_NUMBER_OF_DATASTRUCTURE").setText("0");
47

  
48
		final String officialName = ds.getOfficialName();
49
		conf.addElement("OFFICIAL_NAME").setText(officialName);
50
		String englishName = ds.getEnglishName();
51
		conf.addElement("ENGLISH_NAME").setText(StringUtils.isNotBlank(englishName) ? englishName : officialName);
52
		conf.addElement("ICON_URI").setText(""+ds.getLogoUrl());
53
		conf.addElement("COUNTRY").setText(ds.getCountryCode());
54

  
55
		final Element location = conf.addElement("LOCATION");
56
		location.addElement("LONGITUDE").setText("" + ds.getLongitude());
57
		location.addElement("LATITUDE").setText("" + ds.getLatitude());
58
		location.addElement("TIMEZONE").setText("" + ds.getTimezone());
59

  
60
		conf.addElement("REPOSITORY_WEBPAGE").setText(ds.getWebsiteUrl());
61
		conf.addElement("REPOSITORY_INSTITUTION").setText(ds.getOrganization());
62
		conf.addElement("ADMIN_INFO").setText(ds.getContactEmail());
63

  
64
		final Element ifaces = conf.addElement("INTERFACES");
65
		for (IfaceDesc ifc : ds.getInterfaces()) {
66
			ifaces.add(IfaceDescToNode.convert(ifc));
67
		}
68
		final Element extraFields = conf.addElement("EXTRA_FIELDS");
69
		addExtraField(extraFields, "ACTIVATION_ID", ds.getActivationId());
70
		addExtraField(extraFields, "NamespacePrefix", ds.getNamespacePrefix());
71
		addExtraField(extraFields, "aggregatorName", ds.getAggregator());
72
		addExtraField(extraFields, "dateOfCollection", "" + ds.getDateOfCollection());
73
		addExtraField(extraFields, "dateOfValidation", "" + ds.getDateOfValidation());
74
		conf.addElement("REGISTERED_BY");
75

  
76
		final Element status = body.addElement("STATUS");
77
		status.addElement("NUMBER_OF_OBJECTS").setText("0");
78
		status.addElement("LAST_UPDATE").addAttribute("value", DateUtils.now_ISO8601());
79

  
80
		final Element qos = body.addElement("QOS");
81
		qos.addElement("AVAILABILITY").setText("0");
82
		qos.addElement("CAPACITY");
83
		qos.addElement("THROUGHPUT").setText("0");
84

  
85
		body.addElement("SECURITY_PARAMETERS");
86
		body.addElement("BLACKBOARD");
87

  
88
		return root.asXML();
89
	}
90

  
91
	private static void addExtraField(final Element extraFields, final String field, final String value) {
92
		final Element f = extraFields.addElement("FIELD");
93
		f.addElement("key").setText(field);
94
		f.addElement("value").setText(value != null ? value : "");
95
	}
96

  
97
	@Override
98
	public String apply(final DatasourceDesc ds) {
99
		try {
100
			return DatasourceDescToProfile.convert(ds, environment);
101
		} catch (Exception e) {
102
			log.error("Error convering profile", e);
103
			return null;
104
		}
105
	}
106
}
modules/dnet-datasource-manager-service/trunk/src/main/java/eu/dnetlib/enabling/datasources/ProfileToDatasourceDesc.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import java.io.StringReader;
4

  
5
import org.apache.commons.lang.BooleanUtils;
6
import org.apache.commons.lang.math.NumberUtils;
7
import org.apache.commons.logging.Log;
8
import org.apache.commons.logging.LogFactory;
9
import org.dom4j.Document;
10
import org.dom4j.Element;
11
import org.dom4j.Node;
12
import org.dom4j.io.SAXReader;
13

  
14
import com.google.common.base.Function;
15

  
16
import eu.dnetlib.enabling.datasources.rmi.DatasourceDesc;
17
import eu.dnetlib.enabling.datasources.rmi.IfaceDesc;
18
import eu.dnetlib.miscutils.datetime.DateUtils;
19

  
20
public class ProfileToDatasourceDesc implements Function<String, DatasourceDesc> {
21

  
22
	private static final Log log = LogFactory.getLog(ProfileToDatasourceDesc.class);
23

  
24
	@Override
25
	public DatasourceDesc apply(final String profile) {
26
		try {
27
			return ProfileToDatasourceDesc.convert(profile);
28
		} catch (Exception e) {
29
			log.error("Error convering profile", e);
30
			return null;
31
		}
32
	}
33

  
34
	public static DatasourceDesc convert(final String profile) throws Exception {
35
		final SAXReader reader = new SAXReader();
36
		final Document doc = reader.read(new StringReader(profile));
37

  
38
		final DatasourceDesc ds = new DatasourceDesc();
39
		ds.setId(doc.valueOf("//RESOURCE_IDENTIFIER/@value"));
40
		ds.setDatasourceClass(doc.valueOf("//DATASOURCE_TYPE"));
41
		ds.setTypology(doc.valueOf("//TYPOLOGY"));
42
		ds.setOfficialName(doc.valueOf("//OFFICIAL_NAME"));
43
		ds.setEnglishName(doc.valueOf("//ENGLISH_NAME"));
44
		ds.setCountryCode(doc.valueOf("//COUNTRY"));
45
		ds.setLongitude(NumberUtils.toDouble(doc.valueOf("//LOCATION/LONGITUDE"), 0.0));
46
		ds.setLatitude(NumberUtils.toDouble(doc.valueOf("//LOCATION/LATITUDE"), 0.0));
47
		ds.setTimezone(NumberUtils.toDouble(doc.valueOf("//LOCATION/TIMEZONE"), 0.0));
48
		ds.setWebsiteUrl(doc.valueOf("//REPOSITORY_WEBPAGE"));
49
		ds.setOrganization(doc.valueOf("//REPOSITORY_INSTITUTION"));
50
		ds.setContactEmail(doc.valueOf("//ADMIN_INFO"));
51

  
52
		for (Object o : doc.selectNodes("//INTERFACES/INTERFACE")) {
53
			final Element n = (Element) o;
54

  
55
			final IfaceDesc ifc = new IfaceDesc();
56

  
57
			ifc.setId(n.valueOf("@id"));
58
			ifc.setCompliance(n.valueOf("@compliance"));
59
			ifc.setTypology(n.valueOf("@typology"));
60
			ifc.setContentDescription(n.valueOf("@contentDescription"));
61
			ifc.setActive(BooleanUtils.toBoolean(n.valueOf("@active")));
62
			ifc.setRemovable(BooleanUtils.toBoolean(n.valueOf("@removable")));
63
			ifc.setBaseUrl(n.valueOf("./BASE_URL"));
64
			ifc.setAccessProtocol(n.valueOf("./ACCESS_PROTOCOL"));
65

  
66
			for (Object o1 : n.selectNodes("./ACCESS_PROTOCOL/@*")) {
67
				final Node attr = (Node) o1;
68
				ifc.getAccessParams().put(attr.getName(), attr.getText());
69
			}
70
			for (Object o1 : n.selectNodes("./INTERFACE_EXTRA_FIELD")) {
71
				final Node f = (Node) o1;
72
				ifc.getExtraFields().put(f.valueOf("@name"), f.getText());
73
			}
74

  
75
			ds.getInterfaces().add(ifc);
76
		}
77

  
78
		final DateUtils dateUtils = new DateUtils();
79
		for (Object o : doc.selectNodes("//EXTRA_FIELDS/EXTRA_FIELD")) {
80
			final String k = ((Element) o).valueOf("./key").trim();
81
			final String v = ((Element) o).valueOf("./value").trim();
82

  
83
			if (k.equalsIgnoreCase("ACTIVATION_ID")) {
84
				ds.setActivationId(v);
85
			} else if (k.equalsIgnoreCase("NamespacePrefix")) {
86
				ds.setNamespacePrefix(v);
87
			} else if (k.equalsIgnoreCase("aggregatorName")) {
88
				ds.setAggregator(v);
89
			} else if (k.equalsIgnoreCase("dateOfCollection")) {
90
				ds.setDateOfCollection(dateUtils.parse(v));
91
			} else if (k.equalsIgnoreCase("dateOfValidation")) {
92
				ds.setDateOfValidation(dateUtils.parse(v));
93
			}
94
		}
95

  
96
		return ds;
97
	}
98
}
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/applicationContext-datasource-manager-service.properties
1
dnet.datasource.environment = D-Net
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/applicationContext-datasource-manager-service.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beans xmlns="http://www.springframework.org/schema/beans"
3
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
4
	xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:wsa="http://cxf.apache.org/ws/addressing"
5
	xmlns:p="http://www.springframework.org/schema/p" xmlns:http="http://cxf.apache.org/transports/http/configuration"
6
	xmlns:t="http://dnetlib.eu/springbeans/t" xmlns:template="http://dnetlib.eu/springbeans/template"
7
	xmlns:util="http://www.springframework.org/schema/util"
8
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
9
                                    http://cxf.apache.org/ws/addressing http://cxf.apache.org/schemas/ws-addr-conf.xsd
10
                                    http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
11
                                    http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
12
                            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
13
                            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
14
                            http://dnetlib.eu/springbeans/template http://dnetlib.eu/springbeans/template.xsd">
15

  
16
	<bean id="datasourceManagerService"
17
		class="eu.dnetlib.enabling.datasources.DatasourceManagerServiceImpl" p:environment="${dnet.datasource.environment}">
18
		<property name="browsableFields">
19
			<list>
20
				<bean class="eu.dnetlib.enabling.datasources.XmlBrowsableField"
21
					p:id="country" p:label="Datasource countries" p:xpath="../../COUNTRY/text()"
22
					p:vocabulary="dnet:countries" />
23
				<bean class="eu.dnetlib.enabling.datasources.XmlBrowsableField"
24
					p:id="type" p:label="API typologies" p:xpath="@typology/string()"
25
					p:vocabulary="dnet:datasource_typologies" />
26
				<bean class="eu.dnetlib.enabling.datasources.XmlBrowsableField"
27
					p:id="protocol" p:label="API protocols" p:xpath="ACCESS_PROTOCOL/text()"
28
					p:vocabulary="dnet:protocols" />
29
				<bean class="eu.dnetlib.enabling.datasources.XmlBrowsableField"
30
					p:id="compliance" p:label="API compatibility levels"
31
					p:xpath="concat(substring(./INTERFACE_EXTRA_FIELD[@name='overriding_compliance'], 1, number(boolean(./INTERFACE_EXTRA_FIELD[@name='overriding_compliance'])) * string-length(./INTERFACE_EXTRA_FIELD[@name='overriding_compliance'])), substring(@compliance, 1, number(not(boolean(./INTERFACE_EXTRA_FIELD[@name='overriding_compliance']))) * string-length(@compliance)))"
32
					p:vocabulary="dnet:compatibilityLevel" />
33
			</list>
34
		</property>
35
	</bean>
36

  
37
	<!-- endpoints -->
38
	<jaxws:endpoint id="datasourceManagerServiceEndpoint"
39
		implementor="#datasourceManagerService"
40
		implementorClass="eu.dnetlib.enabling.datasources.rmi.DatasourceManagerService"
41
		address="/datasourceManager" />
42

  
43
	<template:instance name="serviceRegistrationManager"
44
		t:serviceRegistrationManagerClass="eu.dnetlib.enabling.tools.registration.ValidatingServiceRegistrationManagerImpl"
45
		t:name="datasourceManagerServiceRegistrationManager" t:service="datasourceManagerService"
46
		t:endpoint="datasourceManagerServiceEndpoint" t:jobScheduler="jobScheduler" />
47

  
48
</beans>
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/templates/findReposMap.xquery
1
for $x in
2
	collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')
3
where 
4
	$x//NUMBER_OF_OBJECTS != 0 and not($x//LATITUDE = 0 and $x//LONGITUDE = 0) 
5
return 
6
<ds>
7
	<dsId>{$x//RESOURCE_IDENTIFIER/@value/string()}</dsId>
8
	<name>{$x//OFFICIAL_NAME/text()}</name>
9
	<lat>{$x//LATITUDE/text()}</lat>
10
	<lng>{$x//LONGITUDE/text()}</lng>
11
</ds>
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/templates/findRepoApis.xquery.st
1
for \$x in 
2
collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')//INTERFACE[$cond$]
3
return 
4
	<ROW>
5
		<REPO 
6
			id="{\$x/../../../../HEADER/RESOURCE_IDENTIFIER/@value/string()}" 
7
			name="{\$x/../../OFFICIAL_NAME/text()}" 
8
			country="{\$x/../../COUNTRY/text()}" 
9
			prefix="{\$x/../..//EXTRA_FIELDS/FIELD[./key='NamespacePrefix']/value}" />
10
		{\$x}
11
	</ROW>
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/templates/simpleFindRepos.xquery.st
1
for \$x in
2
	collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')
3
where
4
	\$x//DATASOURCE_TYPE = '$type$'
5
return
6
	concat(\$x//RESOURCE_IDENTIFIER/@value, ' @=@ ', \$x//OFFICIAL_NAME, ' @=@ ', \$x//DATASOURCE_ORIGINAL_ID, ' @=@ ', string-join(\$x//INTERFACE/@id, ','), ' @=@ true'),
7
for \$x in
8
	collection('/db/DRIVER/PendingRepositoryResources/RepositoryServiceResourceType')
9
where
10
	\$x//DATASOURCE_TYPE = '$type$'
11
return
12
	concat(\$x//RESOURCE_IDENTIFIER/@value, ' @=@ ', \$x//OFFICIAL_NAME, ' @=@ ', \$x//DATASOURCE_ORIGINAL_ID, ' @=@ ', string-join(\$x//INTERFACE/@id, ','), ' @=@ false')
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/templates/browseRepoApis.xquery.st
1
let \$list := collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')//INTERFACE/$xpath$
2

  
3
for \$x in distinct-values(\$list) 
4
where string-length(\$x) > 0
5
return concat(\$x, ' @-@-@ ', count(\$list[.=\$x]))
modules/dnet-datasource-manager-service/trunk/src/main/resources/eu/dnetlib/enabling/datasources/templates/findRepos.xquery.st
1
for \$x in collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')
2
$if(conds)$
3
	where $conds.keys:{xpath| \$x$xpath$ = '$conds.(xpath)$'}; separator=" and "$
4
$endif$
5
return \$x
6
,
7
for \$x in collection('/db/DRIVER/PendingRepositoryResources/RepositoryServiceResourceType')
8
$if(conds)$
9
	where $conds.keys:{xpath| \$x$xpath$ = '$conds.(xpath)$'}; separator=" and "$
10
$endif$
11
return \$x
modules/dnet-datasource-manager-service/trunk/.springBeans
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beansProjectDescription>
3
	<version>1</version>
4
	<pluginVersion><![CDATA[3.6.2.201410090854-RELEASE]]></pluginVersion>
5
	<configSuffixes>
6
		<configSuffix><![CDATA[xml]]></configSuffix>
7
	</configSuffixes>
8
	<enableImports><![CDATA[false]]></enableImports>
9
	<configs>
10
		<config>src/main/resources/eu/dnetlib/enabling/datasources/applicationContext-datasource-manager-service.xml</config>
11
	</configs>
12
	<autoconfigs>
13
	</autoconfigs>
14
	<configSets>
15
	</configSets>
16
</beansProjectDescription>
modules/dnet-datasource-manager-service/trunk/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<parent>
4
    		<groupId>eu.dnetlib</groupId>
5
	        <artifactId>dnet-parent</artifactId>
6
                <version>1.0.0</version>
7
  	</parent>
8
	<modelVersion>4.0.0</modelVersion>
9
	<groupId>eu.dnetlib</groupId>
10
	<artifactId>dnet-datasource-manager-service</artifactId>
11
	<packaging>jar</packaging>
12
	<version>1.0.7-SNAPSHOT</version>
13
	<scm>
14
		<developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-datasource-manager-service/trunk</developerConnection>
15
	</scm>
16
	<dependencies>
17
		<dependency>
18
			<groupId>eu.dnetlib</groupId>
19
			<artifactId>dnet-datasource-manager-rmi</artifactId>
20
			<version>[4.0.0, 5.0.0)</version>
21
		</dependency>
22
		<dependency>
23
			<groupId>eu.dnetlib</groupId>
24
			<artifactId>cnr-service-common</artifactId>
25
			<version>[2.1.0,3.0.0)</version>
26
		</dependency>
27
		<dependency>
28
  		    <groupId>junit</groupId>
29
    		    <artifactId>junit</artifactId>
30
      		    <version>${junit.version}</version>
31
	            <scope>test</scope>
32
    		</dependency>
33
	</dependencies>
34
</project>
modules/dnet-datasource-manager-service/tags/dnet-datasource-manager-service-1.0.0/deploy.info
1
{"type_source": "SVN", "goal": "package -U -T 4C source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-datasource-manager-service/trunk/", "deploy_repository": "dnet4-snapshots", "version": "4", "mail": "sandro.labruzzo@isti.cnr.it,michele.artini@isti.cnr.it, claudio.atzori@isti.cnr.it, alessia.bardi@isti.cnr.it", "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet4-snapshots", "name": "dnet-datasource-manager-service"}
modules/dnet-datasource-manager-service/tags/dnet-datasource-manager-service-1.0.0/src/main/java/eu/dnetlib/enabling/datasources/IfaceDescToNode.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import java.util.Map.Entry;
4

  
5
import org.dom4j.DocumentHelper;
6
import org.dom4j.Element;
7

  
8
import eu.dnetlib.enabling.datasources.rmi.IfaceDesc;
9

  
10
public class IfaceDescToNode {
11

  
12
	public static Element convert(final IfaceDesc iface) throws Exception {
13

  
14
		final Element ifcNode = DocumentHelper.createElement("INTERFACE");
15
		ifcNode.addAttribute("id", iface.getId());
16
		ifcNode.addAttribute("label", iface.getTypology() + " (" + iface.getCompliance() + ")");
17
		ifcNode.addAttribute("compliance", iface.getCompliance());
18
		ifcNode.addAttribute("typology", iface.getTypology());
19
		ifcNode.addAttribute("contentDescription", iface.getContentDescription());
20
		ifcNode.addAttribute("active", Boolean.toString(iface.getActive()));
21
		ifcNode.addAttribute("removable", Boolean.toString(iface.getRemovable()));
22

  
23
		final Element acProtoNode = ifcNode.addElement("ACCESS_PROTOCOL");
24

  
25
		for (Entry<String, String> e : iface.getAccessParams().entrySet()) {
26
			acProtoNode.addAttribute(e.getKey(), e.getValue());
27
		}
28
		acProtoNode.setText(iface.getAccessProtocol());
29

  
30
		ifcNode.addElement("BASE_URL").setText(iface.getBaseUrl());;
31

  
32
		for (Entry<String, String> e : iface.getExtraFields().entrySet()) {
33
			final Element field = ifcNode.addElement("INTERFACE_EXTRA_FIELD");
34
			field.addAttribute("name", e.getKey());
35
			field.setText(e.getValue());
36
		}
37

  
38
		return ifcNode;
39
	}
40
}
modules/dnet-datasource-manager-service/tags/dnet-datasource-manager-service-1.0.0/src/main/java/eu/dnetlib/enabling/datasources/XmlBrowsableField.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import eu.dnetlib.enabling.datasources.rmi.BrowsableField;
4

  
5
public class XmlBrowsableField extends BrowsableField {
6

  
7
	private String xpath;
8
	private String vocabulary;
9

  
10
	public XmlBrowsableField() {
11
		super();
12
	}
13

  
14
	public XmlBrowsableField(final String id, final String label) {
15
		super(id, label);
16
	}
17

  
18
	public XmlBrowsableField(final String id, final String label, final String xpath, final String vocabulary) {
19
		super(id, label);
20
		this.xpath = xpath;
21
		this.vocabulary = vocabulary;
22
	}
23

  
24
	public String getXpath() {
25
		return xpath;
26
	}
27

  
28
	public void setXpath(final String xpath) {
29
		this.xpath = xpath;
30
	}
31

  
32
	public String getVocabulary() {
33
		return vocabulary;
34
	}
35

  
36
	public void setVocabulary(final String vocabulary) {
37
		this.vocabulary = vocabulary;
38
	}
39

  
40
}
modules/dnet-datasource-manager-service/tags/dnet-datasource-manager-service-1.0.0/src/main/java/eu/dnetlib/enabling/datasources/DatasourceManagerServiceImpl.java
1
package eu.dnetlib.enabling.datasources;
2

  
3
import java.io.StringReader;
4
import java.text.ParseException;
5
import java.util.Collections;
6
import java.util.Date;
7
import java.util.List;
8
import java.util.Map;
9

  
10
import javax.annotation.Resource;
11

  
12
import org.antlr.stringtemplate.StringTemplate;
13
import org.apache.commons.io.IOUtils;
14
import org.apache.commons.lang.StringEscapeUtils;
15
import org.apache.commons.lang.StringUtils;
16
import org.apache.commons.lang.math.NumberUtils;
17
import org.apache.commons.logging.Log;
18
import org.apache.commons.logging.LogFactory;
19
import org.dom4j.Document;
20
import org.dom4j.Element;
21
import org.dom4j.Node;
22
import org.dom4j.io.SAXReader;
23
import org.quartz.CronExpression;
24
import org.springframework.beans.factory.annotation.Required;
25
import org.springframework.core.io.ClassPathResource;
26

  
27
import com.google.common.base.Function;
28
import com.google.common.collect.Lists;
29
import com.google.common.collect.Maps;
30
import com.google.common.collect.Sets;
31

  
32
import eu.dnetlib.enabling.datasources.rmi.BrowsableField;
33
import eu.dnetlib.enabling.datasources.rmi.BrowseTerm;
34
import eu.dnetlib.enabling.datasources.rmi.DatasourceConstants;
35
import eu.dnetlib.enabling.datasources.rmi.DatasourceDesc;
36
import eu.dnetlib.enabling.datasources.rmi.DatasourceManagerService;
37
import eu.dnetlib.enabling.datasources.rmi.DatasourceManagerServiceException;
38
import eu.dnetlib.enabling.datasources.rmi.IfaceDesc;
39
import eu.dnetlib.enabling.datasources.rmi.RepositoryMapEntry;
40
import eu.dnetlib.enabling.datasources.rmi.SearchInterfacesEntry;
41
import eu.dnetlib.enabling.datasources.rmi.SimpleDatasourceDesc;
42
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
43
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
44
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
45
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryException;
46
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
47
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
48
import eu.dnetlib.enabling.tools.AbstractBaseService;
49

  
50
public class DatasourceManagerServiceImpl extends AbstractBaseService implements DatasourceManagerService {
51

  
52
	private static final Log log = LogFactory.getLog(DatasourceManagerServiceImpl.class);
53

  
54
	private static final String REPOSITORY_RESOURCE_TYPE = "RepositoryServiceResourceType";
55

  
56
	private List<XmlBrowsableField> browsableFields;
57

  
58
	private ClassPathResource findReposQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/findRepos.xquery.st");
59

  
60
	private ClassPathResource browseRepoApisQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/browseRepoApis.xquery.st");
61
	private ClassPathResource findRepoApisQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/findRepoApis.xquery.st");
62
	private ClassPathResource findReposMapQuery = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/findReposMap.xquery");
63
	private ClassPathResource simpleFindReposQueryTmpl = new ClassPathResource("/eu/dnetlib/enabling/datasources/templates/simpleFindRepos.xquery.st");
64

  
65
	@Resource
66
	private UniqueServiceLocator serviceLocator;
67

  
68
	@Override
69
	public boolean addDatasource(final DatasourceDesc ds) throws DatasourceManagerServiceException {
70
		try {
71
			final String profile = DatasourceDescToProfile.convert(ds);
72
			serviceLocator.getService(ISRegistryService.class).registerProfile(profile);
73
			return true;
74
		} catch (Exception e) {
75
			log.error("Error registering profile", e);
76
			throw new DatasourceManagerServiceException("Error registering profile", e);
77
		}
78
	}
79

  
80
	@Override
81
	public boolean deleteDatasource(final String dsId) throws DatasourceManagerServiceException {
82
		try {
83
			return serviceLocator.getService(ISRegistryService.class).deleteProfile(dsId);
84
		} catch (ISRegistryException e) {
85
			log.error("Error deleting profile " + dsId, e);
86
			throw new DatasourceManagerServiceException("Error deleting profile " + dsId, e);
87
		}
88
	}
89

  
90
	@Override
91
	public DatasourceDesc getDatasource(final String dsId) throws DatasourceManagerServiceException {
92
		try {
93
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(dsId);
94
			return ProfileToDatasourceDesc.convert(profile);
95
		} catch (Exception e) {
96
			log.error("Error accessing profile " + dsId, e);
97
			throw new DatasourceManagerServiceException("Error accessing profile " + dsId, e);
98
		}
99
	}
100

  
101
	@Override
102
	public List<DatasourceDesc> listAllDatasources() throws DatasourceManagerServiceException {
103
		return listDatasourcesUsingFilter(null, null, null, null);
104
	}
105

  
106
	@Override
107
	public List<DatasourceDesc> listDatasourcesUsingFilter(final String compliance,
108
			final String contentDescription,
109
			final String iisProcessingWorkflow,
110
			final String collectedFrom)
111
			throws DatasourceManagerServiceException {
112
		try {
113
			final StringTemplate st = new StringTemplate();
114
			st.setTemplate(IOUtils.toString(findReposQueryTmpl.getInputStream()));
115

  
116
			if (StringUtils.isNotBlank(compliance)) {
117
				st.setAttribute("compliance", compliance);
118
			}
119
			if (StringUtils.isNotBlank(contentDescription)) {
120
				st.setAttribute("contentDescription", contentDescription);
121
			}
122
			if (StringUtils.isNotBlank(iisProcessingWorkflow)) {
123
				st.setAttribute("iisProcessingWorkflow", iisProcessingWorkflow);
124
			}
125
			if (StringUtils.isNotBlank(collectedFrom)) {
126
				st.setAttribute("collectedFrom", collectedFrom);
127
			}
128
			final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(st.toString());
129

  
130
			return Lists.transform(list, new ProfileToDatasourceDesc());
131
		} catch (Exception e) {
132
			log.error("Error listing datasources", e);
133
			throw new DatasourceManagerServiceException("Error listing datasources", e);
134
		}
135
	}
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff