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