1
|
package eu.dnetlib.repo.manager.service.controllers;
|
2
|
|
3
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
4
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
5
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
6
|
import eu.dnetlib.domain.data.Repository;
|
7
|
import eu.dnetlib.domain.data.RepositoryInterface;
|
8
|
import eu.dnetlib.domain.enabling.Vocabulary;
|
9
|
import eu.dnetlib.repo.manager.service.domain.RequestFilter;
|
10
|
import eu.dnetlib.repo.manager.service.exception.ResourceNotFoundException;
|
11
|
import eu.dnetlib.repo.manager.service.utils.Converter;
|
12
|
import eu.dnetlib.repo.manager.shared.*;
|
13
|
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
|
14
|
import org.apache.commons.codec.digest.DigestUtils;
|
15
|
import org.apache.log4j.Logger;
|
16
|
import org.json.JSONArray;
|
17
|
import org.json.JSONException;
|
18
|
import org.json.JSONObject;
|
19
|
import org.springframework.beans.factory.annotation.Autowired;
|
20
|
import org.springframework.beans.factory.annotation.Value;
|
21
|
import org.springframework.core.ParameterizedTypeReference;
|
22
|
import org.springframework.http.HttpEntity;
|
23
|
import org.springframework.http.HttpHeaders;
|
24
|
import org.springframework.http.HttpMethod;
|
25
|
import org.springframework.http.ResponseEntity;
|
26
|
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
27
|
import org.springframework.security.access.annotation.Secured;
|
28
|
import org.springframework.security.access.prepost.PostAuthorize;
|
29
|
import org.springframework.security.access.prepost.PreAuthorize;
|
30
|
import org.springframework.stereotype.Component;
|
31
|
import org.springframework.web.bind.annotation.PathVariable;
|
32
|
import org.springframework.web.bind.annotation.RequestBody;
|
33
|
import org.springframework.web.bind.annotation.RequestParam;
|
34
|
import org.springframework.web.client.RestClientException;
|
35
|
import org.springframework.web.client.RestTemplate;
|
36
|
import org.springframework.web.util.UriComponents;
|
37
|
import org.springframework.web.util.UriComponentsBuilder;
|
38
|
|
39
|
import javax.annotation.PostConstruct;
|
40
|
import java.sql.Timestamp;
|
41
|
import java.util.*;
|
42
|
import java.util.concurrent.ConcurrentHashMap;
|
43
|
import java.util.function.Function;
|
44
|
import java.util.stream.Collectors;
|
45
|
|
46
|
@Component
|
47
|
public class RepositoryApiImpl implements RepositoryApi {
|
48
|
|
49
|
@Value("${api.baseAddress}")
|
50
|
private String baseAddress;
|
51
|
|
52
|
private RestTemplate restTemplate = null;
|
53
|
|
54
|
private HttpHeaders httpHeaders;
|
55
|
|
56
|
private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
|
57
|
|
58
|
private static final Logger LOGGER = Logger.getLogger(RepositoryApiImpl.class);
|
59
|
|
60
|
@Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
|
61
|
private String usageStatisticsDiagramsBaseURL;
|
62
|
|
63
|
@Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
|
64
|
private String usageStatisticsNumbersBaseURL;
|
65
|
|
66
|
@Autowired
|
67
|
private VocabularyLoader vocabularyLoader;
|
68
|
|
69
|
@Autowired
|
70
|
private PiWikApi piWikApi;
|
71
|
|
72
|
@Autowired
|
73
|
private EmailUtils emailUtils;
|
74
|
|
75
|
private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
|
76
|
|
77
|
private Map<String, String> countriesMap = new HashMap<>();
|
78
|
private Map<String, String> inverseCountriesMap = new HashMap<>();
|
79
|
|
80
|
private static Map<String,List<String>> dataSourceClass = new HashMap<String,List<String>>(){{
|
81
|
put("opendoar",new ArrayList<String>(){{ add("pubsrepository::institutional");
|
82
|
add("pubsrepository::thematic");
|
83
|
add("pubsrepository::unknown");
|
84
|
add("pubsrepository::mock");
|
85
|
}});
|
86
|
put("re3data",new ArrayList<String>(){{ add("datarepository::unknown");
|
87
|
}});
|
88
|
put("journal",new ArrayList<String>(){{ add("pubsrepository::journal");
|
89
|
}});
|
90
|
put("aggregator",new ArrayList<String>(){{ add("aggregator::pubsrepository::institutional");
|
91
|
add("aggregator::pubsrepository::journals");
|
92
|
add("aggregator::datarepository");
|
93
|
add("aggregator::pubsrepository::unknown");
|
94
|
}});
|
95
|
}};
|
96
|
|
97
|
private static Map<String,String> invertedDataSourceClass = new HashMap<String,String>(){{
|
98
|
put("pubsrepository::institutional","opendoar");
|
99
|
put("pubsrepository::thematic","opendoar");
|
100
|
put("pubsrepository::unknown","opendoar");
|
101
|
put("pubsrepository::mock","opendoar");
|
102
|
|
103
|
put("datarepository::unknown","re3data");
|
104
|
|
105
|
put("pubsrepository::journal","journal");
|
106
|
|
107
|
put("aggregator::pubsrepository::institutional","aggregator");
|
108
|
put("aggregator::pubsrepository::journals","aggregator");
|
109
|
put("aggregator::datarepository","aggregator");
|
110
|
put("aggregator::pubsrepository::unknown","aggregator");
|
111
|
|
112
|
}};
|
113
|
|
114
|
|
115
|
|
116
|
@PostConstruct
|
117
|
private void init() {
|
118
|
LOGGER.debug("Initialization method of repository api!");
|
119
|
|
120
|
restTemplate = new RestTemplate();
|
121
|
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
|
122
|
|
123
|
httpHeaders = new HttpHeaders();
|
124
|
httpHeaders.set("Content-Type", "application/json");
|
125
|
|
126
|
for (String vocName : vocabularyNames) {
|
127
|
vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
|
128
|
}
|
129
|
|
130
|
Country[] countries = getCountries();
|
131
|
for (Country c : countries) {
|
132
|
countriesMap.put(c.getName(), c.getCode());
|
133
|
inverseCountriesMap.put(c.getCode(), c.getName());
|
134
|
}
|
135
|
|
136
|
|
137
|
}
|
138
|
|
139
|
@Override
|
140
|
public Country[] getCountries() {
|
141
|
UriComponents uriComponents = UriComponentsBuilder
|
142
|
.fromHttpUrl(baseAddress + "/ds/countries")
|
143
|
.build().encode();
|
144
|
return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
|
145
|
}
|
146
|
|
147
|
|
148
|
@Override
|
149
|
public List<Repository> getRepositoriesByCountry(@PathVariable("country") String country,
|
150
|
@PathVariable("mode") String mode,
|
151
|
@RequestParam(value = "managed",required=false) Boolean managed) throws JSONException {
|
152
|
|
153
|
LOGGER.debug("Getting repositories by country!");
|
154
|
int page = 0;
|
155
|
int size = 100;
|
156
|
List<Repository> resultSet = new ArrayList<>();
|
157
|
|
158
|
String countryCode = countriesMap.get(country);
|
159
|
String filterKey = "UNKNOWN";
|
160
|
if (mode.equalsIgnoreCase("opendoar"))
|
161
|
filterKey = "openaire____::opendoar";
|
162
|
else if (mode.equalsIgnoreCase("re3data"))
|
163
|
filterKey = "openaire____::re3data";
|
164
|
|
165
|
|
166
|
LOGGER.debug("Country code equals : " + countryCode);
|
167
|
LOGGER.debug("Filter mode equals : " + filterKey);
|
168
|
|
169
|
UriComponents uriComponents = searchDatasource(String.valueOf(page),String.valueOf(size));
|
170
|
RequestFilter requestFilter = new RequestFilter();
|
171
|
requestFilter.setCountry(countryCode);
|
172
|
|
173
|
try{
|
174
|
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
175
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
176
|
while (jsonArray.length() > 0 ) {
|
177
|
resultSet.addAll(this.getRepositoriesByMode(filterKey, Converter.jsonToRepositoryList(new JSONObject(rs))));
|
178
|
page += 1;
|
179
|
uriComponents = searchDatasource(String.valueOf(page),String.valueOf(size));
|
180
|
rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
181
|
jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
182
|
}
|
183
|
for (Repository r : resultSet)
|
184
|
this.updateRepositoryInfo(r);
|
185
|
|
186
|
return resultSet;
|
187
|
}catch (Exception e){
|
188
|
LOGGER.debug("Exception on getRepositoriesByCountry" , e);
|
189
|
emailUtils.reportException(e);
|
190
|
throw e;
|
191
|
}
|
192
|
|
193
|
|
194
|
}
|
195
|
|
196
|
private Repository updateRepositoryInfo(Repository r) throws JSONException {
|
197
|
|
198
|
/*
|
199
|
* from datasource class
|
200
|
* we get the datasource type form the inverted map
|
201
|
* */
|
202
|
r.setDatasourceType(getRepositoryType(r.getDatasourceClass()));
|
203
|
r.setInterfaces(this.getRepositoryInterface(r.getId()));
|
204
|
r.setPiwikInfo(piWikApi.getPiwikSiteForRepo(r.getId()));
|
205
|
r.setCountryName(getCountryName(r.getCountryCode()));
|
206
|
return r;
|
207
|
}
|
208
|
|
209
|
|
210
|
private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
|
211
|
|
212
|
List<Repository> reps = new ArrayList<>();
|
213
|
for (Repository r : rs) {
|
214
|
if (r.getCollectedFrom() != null && r.getCollectedFrom().equals(mode))
|
215
|
reps.add(r);
|
216
|
|
217
|
}
|
218
|
return reps;
|
219
|
}
|
220
|
|
221
|
@Override
|
222
|
@PreAuthorize("hasRole('ROLE_USER')")
|
223
|
public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
|
224
|
@PathVariable("page") String page,
|
225
|
@PathVariable("size") String size) throws JSONException {
|
226
|
|
227
|
LOGGER.debug("Retreiving repositories of user : " + userEmail );
|
228
|
UriComponents uriComponents = searchDatasource(page,size);
|
229
|
RequestFilter requestFilter = new RequestFilter();
|
230
|
requestFilter.setRegisteredby(userEmail);
|
231
|
|
232
|
try{
|
233
|
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
234
|
|
235
|
List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
|
236
|
for (Repository r : repos)
|
237
|
this.updateRepositoryInfo(r);
|
238
|
|
239
|
return repos;
|
240
|
}catch (Exception e){
|
241
|
LOGGER.debug("Exception on getRepositoriesOfUser" , e);
|
242
|
emailUtils.reportException(e);
|
243
|
throw e;
|
244
|
}
|
245
|
}
|
246
|
|
247
|
@Override
|
248
|
public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException,ResourceNotFoundException {
|
249
|
|
250
|
LOGGER.debug("Retreiving repositories with id : " + id );
|
251
|
Repository repo = null;
|
252
|
UriComponents uriComponents = searchDatasource("0","100");
|
253
|
RequestFilter requestFilter = new RequestFilter();
|
254
|
requestFilter.setId(id);
|
255
|
|
256
|
try{
|
257
|
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
258
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
259
|
|
260
|
if(jsonArray.length() == 0)
|
261
|
throw new ResourceNotFoundException();
|
262
|
|
263
|
repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
|
264
|
return updateRepositoryInfo(repo);
|
265
|
}catch (JSONException e){
|
266
|
LOGGER.debug("Exception on getRepositoryById" , e);
|
267
|
emailUtils.reportException(e);
|
268
|
throw e;
|
269
|
}
|
270
|
|
271
|
}
|
272
|
|
273
|
|
274
|
@Override
|
275
|
public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
|
276
|
|
277
|
LOGGER.debug("Retreiving aggregations for repository with id : " + id );
|
278
|
UriComponents uriComponents = searchDatasource("0","100");
|
279
|
RequestFilter requestFilter = new RequestFilter();
|
280
|
requestFilter.setId(id);
|
281
|
|
282
|
List<AggregationDetails> aggregationHistory = new ArrayList<>();
|
283
|
|
284
|
try {
|
285
|
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
286
|
JSONObject repository = new JSONObject(rs);
|
287
|
aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
|
288
|
return aggregationHistory.size() == 0? aggregationHistory : aggregationHistory.stream()
|
289
|
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
290
|
.limit(20)
|
291
|
.collect(Collectors.toList());
|
292
|
} catch (JSONException e) {
|
293
|
LOGGER.debug("Exception on getRepositoryAggregations" , e);
|
294
|
emailUtils.reportException(e);
|
295
|
throw e;
|
296
|
}
|
297
|
|
298
|
}
|
299
|
|
300
|
@Override
|
301
|
public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
|
302
|
LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id );
|
303
|
UriComponents uriComponents = searchDatasource("0","100");
|
304
|
RequestFilter requestFilter = new RequestFilter();
|
305
|
requestFilter.setId(id);
|
306
|
|
307
|
List<AggregationDetails> aggregationHistory = new ArrayList<>();
|
308
|
Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
|
309
|
try {
|
310
|
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
311
|
JSONObject repository = new JSONObject(rs);
|
312
|
aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
|
313
|
return aggregationHistory.size() == 0? aggregationByYear:createYearMap(aggregationHistory);
|
314
|
|
315
|
} catch (JSONException e) {
|
316
|
LOGGER.debug("Exception on getRepositoryAggregations" , e);
|
317
|
emailUtils.reportException(e);
|
318
|
throw e;
|
319
|
}
|
320
|
}
|
321
|
|
322
|
private Map<String,List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
|
323
|
Map<String, List<AggregationDetails>> aggregationByYear;
|
324
|
aggregationHistory = aggregationHistory.stream()
|
325
|
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
326
|
.collect(Collectors.toList());
|
327
|
|
328
|
return aggregationHistory.stream()
|
329
|
.collect(Collectors.groupingBy(AggregationDetails::getYear));
|
330
|
}
|
331
|
|
332
|
|
333
|
@Override
|
334
|
public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
|
335
|
@PathVariable("page") String page,
|
336
|
@PathVariable("size") String size) throws JSONException {
|
337
|
|
338
|
LOGGER.debug("Retreiving repositories with official name : " + name );
|
339
|
UriComponents uriComponents = searchDatasource("0","100");
|
340
|
RequestFilter requestFilter = new RequestFilter();
|
341
|
requestFilter.setOfficialname(name);
|
342
|
|
343
|
try{
|
344
|
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
345
|
List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
|
346
|
for (Repository r : repos)
|
347
|
updateRepositoryInfo(r);
|
348
|
return repos;
|
349
|
}catch (Exception e){
|
350
|
LOGGER.debug("Exception on getRepositoriesByName" , e);
|
351
|
emailUtils.reportException(e);
|
352
|
throw e;
|
353
|
}
|
354
|
|
355
|
}
|
356
|
|
357
|
@Override
|
358
|
public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
|
359
|
|
360
|
UriComponents uriComponents = UriComponentsBuilder
|
361
|
.fromHttpUrl(baseAddress + "/ds/api/")
|
362
|
.path("/{id}")
|
363
|
.build().expand(id).encode();
|
364
|
|
365
|
try{
|
366
|
String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
|
367
|
return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
|
368
|
}catch (Exception e ){
|
369
|
LOGGER.debug("Exception on getRepositoryInterface" , e);
|
370
|
emailUtils.reportException(e);
|
371
|
throw e;
|
372
|
}
|
373
|
|
374
|
}
|
375
|
|
376
|
@Override
|
377
|
@PreAuthorize("hasRole('ROLE_USER') and #repository.registeredBy == authentication.userInfo.email")
|
378
|
public Repository addRepository(@RequestParam("datatype") String datatype,
|
379
|
@RequestBody Repository repository) throws Exception {
|
380
|
|
381
|
repository = this.setRepositoryFeatures(datatype,repository);
|
382
|
LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
|
383
|
this.storeRepository(repository);
|
384
|
return repository;
|
385
|
}
|
386
|
|
387
|
@Override
|
388
|
@PreAuthorize("hasRole('ROLE_USER') and #repository.registeredBy == authentication.userInfo.email")
|
389
|
public Repository updateRepository(@RequestBody Repository repository) throws JSONException {
|
390
|
UriComponents uriComponents = UriComponentsBuilder
|
391
|
.fromHttpUrl(baseAddress + "/ds/update/")
|
392
|
.build()
|
393
|
.encode();
|
394
|
|
395
|
try {
|
396
|
String json_repository = Converter.repositoryObjectToJson(repository);
|
397
|
HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
|
398
|
restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
|
399
|
return repository;
|
400
|
}catch (Exception e){
|
401
|
LOGGER.debug("Exception on updateRepository" , e);
|
402
|
emailUtils.reportException(e);
|
403
|
throw e;
|
404
|
}
|
405
|
|
406
|
}
|
407
|
|
408
|
private Repository setRepositoryFeatures(String datatype, Repository repository) {
|
409
|
|
410
|
//TODO update map
|
411
|
repository.setCountryCode(countriesMap.get(repository.getCountryName()));
|
412
|
repository.setActivationId(UUID.randomUUID().toString());
|
413
|
repository.setCollectedFrom("infrastruct_::openaire");
|
414
|
|
415
|
if (datatype.equals("journal")) {
|
416
|
repository.setId("openaire____::issn" + repository.getIssn());
|
417
|
repository.setNamespacePrefix("issn" + repository.getIssn());
|
418
|
}else if (datatype.equals("aggregator")) {
|
419
|
repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
|
420
|
repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0,12));
|
421
|
}
|
422
|
|
423
|
return repository;
|
424
|
}
|
425
|
|
426
|
private void updateInterface(String datatype,RepositoryInterface iFace) {
|
427
|
//TODO call update base url
|
428
|
//((DatasourceManagerService) this.dmService.getService()).updateBaseUrl(repo.getId(), iFace.getId(), iFace.getBaseUrl());
|
429
|
if (!iFace.getAccessSet().isEmpty()) {
|
430
|
LOGGER.debug("set not empty: " + iFace.getAccessSet());
|
431
|
//TODO call update method for access params
|
432
|
// ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "set", iFace.getAccessSet(), false);
|
433
|
} else {
|
434
|
//TODO call deleteAccessParamOrExtraField
|
435
|
//((DatasourceManagerService) this.dmService.getService()).deleteAccessParamOrExtraField(repo.getId(), iFace.getId(), "set");
|
436
|
}
|
437
|
//TODO update content description
|
438
|
//((DatasourceManagerService) this.dmService.getService()).updateContentDescription(repo.getId(), iFace.getId(), "metadata");
|
439
|
if (datatype.equals("re3data")) {
|
440
|
//TODO call update access params
|
441
|
// ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_datacite", false);
|
442
|
iFace.setAccessFormat("oai_datacite");
|
443
|
} else {
|
444
|
//TODO call update access params
|
445
|
//((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_dc", false);
|
446
|
iFace.setAccessFormat("oai_dc");
|
447
|
}
|
448
|
|
449
|
}
|
450
|
|
451
|
private void storeRepository(Repository repository) throws JSONException {
|
452
|
|
453
|
Date utilDate = new Date();
|
454
|
Timestamp date = new Timestamp(utilDate.getTime());
|
455
|
repository.setDateOfCollection(date);
|
456
|
repository.setAggregator("OPENAIRE");
|
457
|
repository.setCountryCode(countriesMap.get(repository.getCountryName()));
|
458
|
|
459
|
UriComponents uriComponents = UriComponentsBuilder
|
460
|
.fromHttpUrl(baseAddress + "/ds/add/")
|
461
|
.build()
|
462
|
.encode();
|
463
|
String json_repository = Converter.repositoryObjectToJson(repository);
|
464
|
|
465
|
ObjectMapper mapper = new ObjectMapper();
|
466
|
mapper.enable(SerializationFeature.INDENT_OUTPUT);
|
467
|
try {
|
468
|
LOGGER.debug(mapper.writeValueAsString(json_repository));
|
469
|
} catch (JsonProcessingException e) {
|
470
|
e.printStackTrace();
|
471
|
}
|
472
|
|
473
|
HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
|
474
|
restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
|
475
|
}
|
476
|
|
477
|
@Override
|
478
|
@PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
|
479
|
public void deleteRepositoryInterface(@RequestParam("id") String id ,
|
480
|
@RequestParam("registeredBy") String registeredBy){
|
481
|
UriComponents uriComponents = UriComponentsBuilder
|
482
|
.fromHttpUrl(baseAddress + "/ds/api/")
|
483
|
.path("/{id}")
|
484
|
.build().expand(id).encode();
|
485
|
LOGGER.debug(uriComponents.toUri());
|
486
|
restTemplate.delete(uriComponents.toUri());
|
487
|
}
|
488
|
|
489
|
@Override
|
490
|
@PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
|
491
|
public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
|
492
|
@RequestParam("repoId") String repoId,
|
493
|
@RequestParam("registeredBy") String registeredBy,
|
494
|
@RequestBody RepositoryInterface repositoryInterface) throws JSONException,ResourceNotFoundException {
|
495
|
try {
|
496
|
Repository e = this.getRepositoryById(repoId);
|
497
|
repositoryInterface = createRepositoryInterface(e,repositoryInterface,datatype);
|
498
|
String json_interface = Converter.repositoryInterfaceObjectToJson(e,repositoryInterface);
|
499
|
|
500
|
UriComponents uriComponents = UriComponentsBuilder
|
501
|
.fromHttpUrl(baseAddress + "/ds/api/add/")
|
502
|
.build()
|
503
|
.encode();
|
504
|
|
505
|
HttpEntity<String> httpEntity = new HttpEntity <String> (json_interface,httpHeaders);
|
506
|
restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
|
507
|
return repositoryInterface;
|
508
|
|
509
|
} catch (JSONException e) {
|
510
|
LOGGER.debug("Exception on addRepositoryInterface" , e);
|
511
|
emailUtils.reportException(e);
|
512
|
throw e;
|
513
|
}
|
514
|
}
|
515
|
|
516
|
private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
|
517
|
|
518
|
iFace.setContentDescription("metadata");
|
519
|
iFace.setCompliance("UNKNOWN");
|
520
|
|
521
|
if (datatype.equals("re3data"))
|
522
|
iFace.setAccessFormat("oai_datacite");
|
523
|
else
|
524
|
iFace.setAccessFormat("oai_dc");
|
525
|
|
526
|
|
527
|
if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty())
|
528
|
iFace.setTypology(repo.getDatasourceClass());
|
529
|
else if (datatype.equalsIgnoreCase("journal"))
|
530
|
iFace.setTypology("pubsrepository::journal");
|
531
|
else if (datatype.equalsIgnoreCase("aggregator"))
|
532
|
iFace.setTypology("aggregator::pubsrepository::unknown");
|
533
|
else if (datatype.equalsIgnoreCase("opendoar"))
|
534
|
iFace.setTypology("pubsrepository::unknown");
|
535
|
else if (datatype.equalsIgnoreCase("re3data"))
|
536
|
iFace.setTypology("datarepository::unknown");
|
537
|
|
538
|
iFace.setRemovable(true);
|
539
|
iFace.setAccessProtocol("oai");
|
540
|
iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
|
541
|
iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
|
542
|
if (iFace.getAccessSet().isEmpty()) {
|
543
|
LOGGER.debug("set is empty: " + iFace.getAccessSet());
|
544
|
iFace.removeAccessSet();
|
545
|
}
|
546
|
return iFace;
|
547
|
}
|
548
|
|
549
|
@Override
|
550
|
public List<String> getDnetCountries() {
|
551
|
LOGGER.debug("Getting dnet-countries!");
|
552
|
return Converter.readFile("countries.txt");
|
553
|
}
|
554
|
|
555
|
@Override
|
556
|
public List<String> getTypologies() {
|
557
|
return Converter.readFile("typologies.txt");
|
558
|
}
|
559
|
|
560
|
@Override
|
561
|
public List<Timezone> getTimezones() {
|
562
|
List<String> timezones = Converter.readFile("timezones.txt");
|
563
|
return Converter.toTimezones(timezones);
|
564
|
}
|
565
|
|
566
|
@Override
|
567
|
@PreAuthorize("hasRole('ROLE_USER')")
|
568
|
public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String userEmail,
|
569
|
@PathVariable("page") String page,
|
570
|
@PathVariable("size") String size) throws JSONException {
|
571
|
UriComponents uriComponents = UriComponentsBuilder
|
572
|
.fromHttpUrl(baseAddress + "/api/baseurl/")
|
573
|
.path("/{page}/{size}")
|
574
|
.build().expand(page,size).encode();
|
575
|
|
576
|
try{
|
577
|
RequestFilter requestFilter = new RequestFilter();
|
578
|
requestFilter.setRegisteredby(userEmail);
|
579
|
return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(),requestFilter, String[].class));
|
580
|
}catch (Exception e){
|
581
|
LOGGER.debug("Exception on addRepositoryInterface" , e);
|
582
|
emailUtils.reportException(e);
|
583
|
throw e;
|
584
|
}
|
585
|
}
|
586
|
|
587
|
@Override
|
588
|
public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
|
589
|
|
590
|
List<String> resultSet = new ArrayList<>();
|
591
|
for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
|
592
|
if (mode.equalsIgnoreCase("aggregator")) {
|
593
|
if (entry.getKey().contains("aggregator"))
|
594
|
resultSet.add(entry.getValue());
|
595
|
} else if (mode.equalsIgnoreCase("journal")) {
|
596
|
if (entry.getKey().contains("journal"))
|
597
|
resultSet.add(entry.getValue());
|
598
|
} else if (mode.equalsIgnoreCase("opendoar")) {
|
599
|
if (entry.getKey().contains("pubsrepository"))
|
600
|
resultSet.add(entry.getValue());
|
601
|
} else if (mode.equalsIgnoreCase("re3data")) {
|
602
|
if (entry.getKey().contains("datarepository"))
|
603
|
resultSet.add(entry.getValue());
|
604
|
}
|
605
|
}
|
606
|
|
607
|
|
608
|
return resultSet;
|
609
|
}
|
610
|
|
611
|
private Vocabulary getVocabulary(String vocName) {
|
612
|
|
613
|
if (!vocabularyMap.containsKey(vocName)) {
|
614
|
vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
|
615
|
}
|
616
|
return vocabularyMap.get(vocName);
|
617
|
}
|
618
|
|
619
|
|
620
|
@Override
|
621
|
public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
|
622
|
|
623
|
LOGGER.debug("Getting compatibility classes for mode: " + mode);
|
624
|
Map<String, String> retMap = new HashMap<String, String>();
|
625
|
|
626
|
Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
|
627
|
boolean foundData = false;
|
628
|
for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
|
629
|
if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
|
630
|
return compatibilityClasses;
|
631
|
else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
|
632
|
if (entry.getKey().matches("^openaire[1-9].0_data$")) {
|
633
|
retMap.put(entry.getKey(), entry.getValue());
|
634
|
foundData = true;
|
635
|
}
|
636
|
} else {
|
637
|
if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
|
638
|
retMap.put(entry.getKey(), entry.getValue());
|
639
|
}
|
640
|
}
|
641
|
|
642
|
//TODO TO BE REMOVED WHEN VOCABULARIES ARE UPDATED
|
643
|
if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA) && !foundData)
|
644
|
retMap.put("openaire2.0_data", "OpenAIRE Data (funded, referenced datasets)");
|
645
|
|
646
|
return retMap;
|
647
|
}
|
648
|
|
649
|
@Override
|
650
|
public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode) {
|
651
|
|
652
|
LOGGER.debug("Getting datasource classes for mode: " + mode);
|
653
|
|
654
|
Map<String, String> retMap = new HashMap<String, String>();
|
655
|
|
656
|
for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
|
657
|
if (mode.equalsIgnoreCase("aggregator")) {
|
658
|
if (entry.getKey().contains("aggregator"))
|
659
|
retMap.put(entry.getKey(), entry.getValue());
|
660
|
} else if (mode.equalsIgnoreCase("journal")) {
|
661
|
if (entry.getKey().contains("journal"))
|
662
|
retMap.put(entry.getKey(), entry.getValue());
|
663
|
} else if (mode.equalsIgnoreCase("opendoar")) {
|
664
|
if (entry.getKey().contains("pubsrepository"))
|
665
|
retMap.put(entry.getKey(), entry.getValue());
|
666
|
} else if (mode.equalsIgnoreCase("re3data")) {
|
667
|
if (entry.getKey().contains("datarepository"))
|
668
|
retMap.put(entry.getKey(), entry.getValue());
|
669
|
}
|
670
|
}
|
671
|
return filterResults(retMap,mode);
|
672
|
|
673
|
}
|
674
|
|
675
|
private Map<String,String> filterResults(Map<String, String> map,String mode) {
|
676
|
|
677
|
HashMap<String,String> filteredMap = new HashMap<>();
|
678
|
for(String key:map.keySet())
|
679
|
if(dataSourceClass.get(mode).contains(key))
|
680
|
filteredMap.put(key,map.get(key));
|
681
|
|
682
|
return filteredMap;
|
683
|
}
|
684
|
|
685
|
@Override
|
686
|
public String getCountryName(String countryCode) {
|
687
|
return inverseCountriesMap.get(countryCode);
|
688
|
}
|
689
|
|
690
|
@Override
|
691
|
public MetricsInfo getMetricsInfoForRepository(@PathVariable("repoId") String repoId) throws RepositoryServiceException {
|
692
|
try {
|
693
|
|
694
|
MetricsInfo metricsInfo = new MetricsInfo();
|
695
|
metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
|
696
|
metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
|
697
|
return metricsInfo;
|
698
|
|
699
|
} catch (Exception e) {
|
700
|
LOGGER.error("Error while getting metrics info for repository: ", e);
|
701
|
emailUtils.reportException(e);
|
702
|
throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
|
703
|
}
|
704
|
}
|
705
|
|
706
|
@Override
|
707
|
public Map<String, String> getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException {
|
708
|
if(mode.equals("opendoar"))
|
709
|
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(0).getLastCollectionDate());
|
710
|
else
|
711
|
/*
|
712
|
* first api of re3data has null value on collection date
|
713
|
* */
|
714
|
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(1).getLastCollectionDate());
|
715
|
}
|
716
|
|
717
|
@Override
|
718
|
@PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
|
719
|
public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String repoId,
|
720
|
@RequestParam("registeredBy") String registeredBy,
|
721
|
@RequestBody RepositoryInterface repositoryInterface) throws JSONException {
|
722
|
|
723
|
this.updateBaseUrl(repoId,repositoryInterface.getId(),repositoryInterface.getBaseUrl());
|
724
|
this.updateCompliance(repoId,repositoryInterface.getId(),repositoryInterface.getCompliance());
|
725
|
this.updateValidationSet(repoId,repositoryInterface.getId(),repositoryInterface.getAccessSet());
|
726
|
return repositoryInterface;
|
727
|
}
|
728
|
|
729
|
private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) {
|
730
|
UriComponents uriComponents = UriComponentsBuilder
|
731
|
.fromHttpUrl(baseAddress + "/ds/api/oaiset")
|
732
|
.queryParam("dsId",repositoryId)
|
733
|
.queryParam("apiId",repositoryInterfaceId)
|
734
|
.queryParam("oaiSet",validationSet)
|
735
|
.build().encode();
|
736
|
restTemplate.postForObject(uriComponents.toUri(),null,String.class);
|
737
|
}
|
738
|
|
739
|
|
740
|
private void updateBaseUrl(String repositoryId, String repositoryInterfaceId, String baseUrl) {
|
741
|
UriComponents uriComponents = UriComponentsBuilder
|
742
|
.fromHttpUrl(baseAddress + "/ds/api/baseurl")
|
743
|
.queryParam("dsId",repositoryId)
|
744
|
.queryParam("apiId",repositoryInterfaceId)
|
745
|
.queryParam("baseUrl",baseUrl)
|
746
|
.build().encode();
|
747
|
restTemplate.postForObject(uriComponents.toUri(),null,String.class);
|
748
|
}
|
749
|
|
750
|
private void updateCompliance(String repositoryId, String repositoryInterfaceId,String compliance) {
|
751
|
UriComponents uriComponents = UriComponentsBuilder
|
752
|
.fromHttpUrl(baseAddress + "/ds/api/compliance")
|
753
|
.queryParam("dsId",repositoryId)
|
754
|
.queryParam("apiId",repositoryInterfaceId)
|
755
|
.queryParam("compliance",compliance)
|
756
|
.build().encode();
|
757
|
restTemplate.postForObject(uriComponents.toUri(),null,String.class);
|
758
|
}
|
759
|
|
760
|
private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
|
761
|
|
762
|
//build the uri params
|
763
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
|
764
|
|
765
|
//create new template engine
|
766
|
RestTemplate template = new RestTemplate();
|
767
|
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
|
768
|
ResponseEntity<MetricsNumbers> resp;
|
769
|
try {
|
770
|
//communicate with endpoint
|
771
|
resp = template.exchange(
|
772
|
builder.build().encode().toUri(),
|
773
|
HttpMethod.GET,
|
774
|
null,
|
775
|
new ParameterizedTypeReference<MetricsNumbers>() {
|
776
|
});
|
777
|
} catch (RestClientException e) {
|
778
|
LOGGER.debug("Exception on getMetricsNumbers" , e);
|
779
|
emailUtils.reportException(e);
|
780
|
throw e;
|
781
|
}
|
782
|
|
783
|
return resp.getBody();
|
784
|
}
|
785
|
|
786
|
private String getOpenAIREId(String repoId) {
|
787
|
|
788
|
if (repoId != null && repoId.contains("::")) {
|
789
|
return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
|
790
|
}
|
791
|
|
792
|
return null;
|
793
|
}
|
794
|
|
795
|
private UriComponents searchDatasource(String page,String size){
|
796
|
|
797
|
return UriComponentsBuilder
|
798
|
.fromHttpUrl(baseAddress + "/ds/search/")
|
799
|
.path("/{page}/{size}/")
|
800
|
.queryParam("requestSortBy","id")
|
801
|
.queryParam("order","ASCENDING")
|
802
|
.build().expand(page, size).encode();
|
803
|
}
|
804
|
|
805
|
private String getRepositoryType(String typology){
|
806
|
return invertedDataSourceClass.get(typology);
|
807
|
}
|
808
|
|
809
|
|
810
|
}
|