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