1
|
package eu.dnetlib.repo.manager.service;
|
2
|
|
3
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
4
|
import com.google.gson.JsonArray;
|
5
|
import com.google.gson.JsonElement;
|
6
|
import com.google.gson.JsonObject;
|
7
|
import eu.dnetlib.api.functionality.ValidatorServiceException;
|
8
|
import eu.dnetlib.domain.data.Repository;
|
9
|
import eu.dnetlib.domain.data.RepositoryInterface;
|
10
|
import eu.dnetlib.domain.enabling.Vocabulary;
|
11
|
import eu.dnetlib.domain.functionality.validator.JobForValidation;
|
12
|
import eu.dnetlib.repo.manager.domain.*;
|
13
|
import eu.dnetlib.repo.manager.domain.dto.Role;
|
14
|
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
|
15
|
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
|
16
|
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
|
17
|
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
|
18
|
import eu.dnetlib.repo.manager.service.security.RoleMappingService;
|
19
|
import eu.dnetlib.repo.manager.utils.Converter;
|
20
|
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
|
21
|
import org.apache.commons.codec.digest.DigestUtils;
|
22
|
import org.apache.log4j.Logger;
|
23
|
import org.json.JSONArray;
|
24
|
import org.json.JSONException;
|
25
|
import org.json.JSONObject;
|
26
|
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
27
|
import org.springframework.beans.factory.annotation.Autowired;
|
28
|
import org.springframework.beans.factory.annotation.Value;
|
29
|
import org.springframework.context.annotation.Lazy;
|
30
|
import org.springframework.core.ParameterizedTypeReference;
|
31
|
import org.springframework.http.*;
|
32
|
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
33
|
import org.springframework.security.core.Authentication;
|
34
|
import org.springframework.security.core.context.SecurityContextHolder;
|
35
|
import org.springframework.stereotype.Service;
|
36
|
import org.springframework.web.client.HttpClientErrorException;
|
37
|
import org.springframework.web.client.RestClientException;
|
38
|
import org.springframework.web.client.RestTemplate;
|
39
|
import org.springframework.web.util.UriComponents;
|
40
|
import org.springframework.web.util.UriComponentsBuilder;
|
41
|
|
42
|
import javax.annotation.PostConstruct;
|
43
|
import java.io.IOException;
|
44
|
import java.sql.Timestamp;
|
45
|
import java.util.*;
|
46
|
import java.util.concurrent.ConcurrentHashMap;
|
47
|
import java.util.stream.Collectors;
|
48
|
|
49
|
@Service("repositoryService")
|
50
|
public class RepositoryServiceImpl implements RepositoryService {
|
51
|
|
52
|
private static final Logger LOGGER = Logger.getLogger(RepositoryServiceImpl.class);
|
53
|
|
54
|
private final AuthorizationService authorizationService;
|
55
|
private final RoleMappingService roleMappingService;
|
56
|
private final AaiRegistryService registryCalls;
|
57
|
private final AuthoritiesUpdater authoritiesUpdater;
|
58
|
private final RestTemplate restTemplate;
|
59
|
private final VocabularyLoader vocabularyLoader;
|
60
|
private final PiWikService piWikService;
|
61
|
private final EmailUtils emailUtils;
|
62
|
private final ValidatorService validatorService;
|
63
|
|
64
|
@Value("${api.baseAddress}")
|
65
|
private String baseAddress;
|
66
|
|
67
|
@Value("${services.repo-manager.adminEmail}")
|
68
|
private String adminEmail;
|
69
|
|
70
|
@Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
|
71
|
private String usageStatisticsDiagramsBaseURL;
|
72
|
|
73
|
@Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
|
74
|
private String usageStatisticsNumbersBaseURL;
|
75
|
|
76
|
|
77
|
private static final Map<String, List<String>> dataSourceClass = new HashMap<>();
|
78
|
private static final Map<String, String> invertedDataSourceClass = new HashMap<>();
|
79
|
|
80
|
|
81
|
private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
|
82
|
private final Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<>();
|
83
|
private final Map<String, String> countriesMap = new HashMap<>();
|
84
|
private final Map<String, String> inverseCountriesMap = new HashMap<>();
|
85
|
|
86
|
private HttpHeaders httpHeaders;
|
87
|
|
88
|
@Autowired
|
89
|
public RepositoryServiceImpl(AuthorizationService authorizationService,
|
90
|
RoleMappingService roleMappingService,
|
91
|
AaiRegistryService registryCalls,
|
92
|
AuthoritiesUpdater authoritiesUpdater,
|
93
|
VocabularyLoader vocabularyLoader,
|
94
|
RestTemplate restTemplate,
|
95
|
@Lazy EmailUtils emailUtils,
|
96
|
@Lazy ValidatorService validatorService,
|
97
|
@Lazy PiWikService piWikService) {
|
98
|
this.authorizationService = authorizationService;
|
99
|
this.roleMappingService = roleMappingService;
|
100
|
this.registryCalls = registryCalls;
|
101
|
this.authoritiesUpdater = authoritiesUpdater;
|
102
|
this.vocabularyLoader = vocabularyLoader;
|
103
|
this.piWikService = piWikService;
|
104
|
this.emailUtils = emailUtils;
|
105
|
this.validatorService = validatorService;
|
106
|
this.restTemplate = restTemplate;
|
107
|
}
|
108
|
|
109
|
private String getAuthenticatedUserEmail() {
|
110
|
OIDCAuthenticationToken authenticationToken = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
|
111
|
return authenticationToken.getUserInfo().getEmail();
|
112
|
}
|
113
|
|
114
|
|
115
|
@PostConstruct
|
116
|
private void init() {
|
117
|
LOGGER.debug("Initialization method of repository api!");
|
118
|
LOGGER.debug("Updated version!");
|
119
|
|
120
|
dataSourceClass.put("opendoar", Arrays.asList("pubsrepository::institutional", "pubsrepository::thematic", "pubsrepository::unknown", "pubsrepository::mock"));
|
121
|
dataSourceClass.put("re3data", Collections.singletonList("datarepository::unknown"));
|
122
|
dataSourceClass.put("journal", Collections.singletonList("pubsrepository::journal"));
|
123
|
dataSourceClass.put("aggregator", Arrays.asList("aggregator::pubsrepository::institutional", "aggregator::pubsrepository::journals", "aggregator::datarepository", "aggregator::pubsrepository::unknown"));
|
124
|
|
125
|
invertedDataSourceClass.put("pubsrepository::institutional", "opendoar");
|
126
|
invertedDataSourceClass.put("pubsrepository::thematic", "opendoar");
|
127
|
invertedDataSourceClass.put("pubsrepository::unknown", "opendoar");
|
128
|
invertedDataSourceClass.put("pubsrepository::mock", "opendoar");
|
129
|
invertedDataSourceClass.put("datarepository::unknown", "re3data");
|
130
|
invertedDataSourceClass.put("pubsrepository::journal", "journal");
|
131
|
invertedDataSourceClass.put("aggregator::pubsrepository::institutional", "aggregator");
|
132
|
invertedDataSourceClass.put("aggregator::pubsrepository::journals", "aggregator");
|
133
|
invertedDataSourceClass.put("aggregator::datarepository", "aggregator");
|
134
|
invertedDataSourceClass.put("aggregator::pubsrepository::unknown", "aggregator");
|
135
|
|
136
|
|
137
|
httpHeaders = new HttpHeaders();
|
138
|
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
|
139
|
|
140
|
for (String vocName : vocabularyNames) {
|
141
|
vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
|
142
|
}
|
143
|
|
144
|
Country[] countries = getCountries();
|
145
|
for (Country c : countries) {
|
146
|
countriesMap.put(c.getName(), c.getCode());
|
147
|
inverseCountriesMap.put(c.getCode(), c.getName());
|
148
|
}
|
149
|
|
150
|
|
151
|
}
|
152
|
|
153
|
@Override
|
154
|
public Country[] getCountries() {
|
155
|
UriComponents uriComponents = UriComponentsBuilder
|
156
|
.fromHttpUrl(baseAddress + "/ds/countries")
|
157
|
.build().encode();
|
158
|
return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
|
159
|
}
|
160
|
|
161
|
// FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
|
162
|
// and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
|
163
|
// another way for paging must be implemented.
|
164
|
@Override
|
165
|
public List<Repository> getRepositories(List<String> ids) throws JSONException {
|
166
|
return getRepositories(ids, 0, 10);
|
167
|
}
|
168
|
|
169
|
// FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
|
170
|
// and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
|
171
|
// another way for paging must be implemented.
|
172
|
@Override
|
173
|
public List<Repository> getRepositories(List<String> ids, int page, int size) throws JSONException {
|
174
|
List<Repository> repos = new ArrayList<>();
|
175
|
LOGGER.debug("Retreiving repositories with ids : " + String.join(", ", ids));
|
176
|
UriComponents uriComponents = searchDatasource(Integer.toString(Math.abs(page)), Integer.toString(Math.abs(size)));
|
177
|
RequestFilter requestFilter = new RequestFilter();
|
178
|
|
179
|
try {
|
180
|
for (String repoId : ids) {
|
181
|
requestFilter.setId(repoId);
|
182
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
183
|
|
184
|
repos.addAll(Converter.jsonToRepositoryList(new JSONObject(rs)));
|
185
|
}
|
186
|
} catch (JSONException e) {
|
187
|
LOGGER.debug("Exception on getRepositoriesOfUser", e);
|
188
|
emailUtils.reportException(e);
|
189
|
throw e;
|
190
|
}
|
191
|
|
192
|
for (Repository r : repos)
|
193
|
r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
|
194
|
return repos;
|
195
|
}
|
196
|
|
197
|
// FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
|
198
|
// and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
|
199
|
// another way for paging must be implemented.
|
200
|
@Override
|
201
|
public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids) throws Exception {
|
202
|
return getRepositoriesSnippets(ids, 0, 10);
|
203
|
}
|
204
|
|
205
|
// FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
|
206
|
// and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
|
207
|
// another way for paging must be implemented.
|
208
|
@Override
|
209
|
public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids, int page, int size) throws Exception {
|
210
|
List<RepositorySnippet> resultSet = new ArrayList<>();
|
211
|
ObjectMapper mapper = new ObjectMapper();
|
212
|
|
213
|
// here page should be 0
|
214
|
UriComponents uriComponents = searchSnipperDatasource(Integer.toString(Math.abs(page)), Integer.toString(Math.abs(size)));
|
215
|
RequestFilter requestFilter = new RequestFilter();
|
216
|
|
217
|
try {
|
218
|
for (String repoId : ids) {
|
219
|
requestFilter.setId(repoId);
|
220
|
|
221
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
222
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
223
|
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
|
224
|
mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
225
|
}
|
226
|
} catch (Exception e) {
|
227
|
LOGGER.debug("Exception on getRepositoriesSnippetOfUser", e);
|
228
|
throw e;
|
229
|
}
|
230
|
|
231
|
LOGGER.debug("resultSet:" + resultSet);
|
232
|
resultSet.parallelStream().forEach(repositorySnippet -> {
|
233
|
repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId()));
|
234
|
});
|
235
|
return resultSet;
|
236
|
}
|
237
|
|
238
|
|
239
|
@Override
|
240
|
public List<RepositorySnippet> getRepositoriesByCountry(String country,
|
241
|
String mode,
|
242
|
Boolean managed) throws JSONException, IOException {
|
243
|
|
244
|
LOGGER.debug("Getting repositories by country!");
|
245
|
int page = 0;
|
246
|
int size = 100;
|
247
|
List<RepositorySnippet> resultSet = new ArrayList<>();
|
248
|
ObjectMapper mapper = new ObjectMapper();
|
249
|
|
250
|
String filterKey = "UNKNOWN";
|
251
|
if (mode.equalsIgnoreCase("opendoar"))
|
252
|
filterKey = "openaire____::opendoar";
|
253
|
else if (mode.equalsIgnoreCase("re3data"))
|
254
|
filterKey = "openaire____::re3data";
|
255
|
|
256
|
|
257
|
LOGGER.debug("Country code equals : " + country);
|
258
|
LOGGER.debug("Filter mode equals : " + filterKey);
|
259
|
|
260
|
UriComponents uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size));
|
261
|
RequestFilter requestFilter = new RequestFilter();
|
262
|
requestFilter.setCountry(country);
|
263
|
requestFilter.setCollectedfrom(filterKey);
|
264
|
|
265
|
try {
|
266
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
267
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
268
|
while (jsonArray.length() > 0) {
|
269
|
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
|
270
|
mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
271
|
page += 1;
|
272
|
uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size));
|
273
|
rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
274
|
jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
275
|
}
|
276
|
return resultSet;
|
277
|
} catch (Exception e) {
|
278
|
LOGGER.debug("Exception on getRepositoriesByCountry", e);
|
279
|
// emailUtils.reportException(e);
|
280
|
throw e;
|
281
|
}
|
282
|
}
|
283
|
|
284
|
public List<RepositorySnippet> searchRegisteredRepositories(String country, String typology, String englishName,
|
285
|
String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception {
|
286
|
|
287
|
LOGGER.debug("Searching registered repositories");
|
288
|
|
289
|
List<RepositorySnippet> resultSet = new ArrayList<>();
|
290
|
ObjectMapper mapper = new ObjectMapper();
|
291
|
|
292
|
UriComponents uriComponents = searchRegisteredDatasource(requestSortBy, order, Integer.toString(page), Integer.toString(pageSize));
|
293
|
|
294
|
RequestFilter requestFilter = new RequestFilter();
|
295
|
requestFilter.setCountry(country);
|
296
|
requestFilter.setTypology(typology);
|
297
|
requestFilter.setOfficialname(officialName);
|
298
|
requestFilter.setEnglishname(englishName);
|
299
|
|
300
|
try {
|
301
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
302
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
303
|
|
304
|
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray), mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
305
|
|
306
|
return resultSet;
|
307
|
} catch (Exception e) {
|
308
|
LOGGER.error("Error searching registered datasources", e);
|
309
|
throw e;
|
310
|
}
|
311
|
}
|
312
|
|
313
|
private Repository updateRepositoryInfo(Repository r) throws JSONException {
|
314
|
|
315
|
/*
|
316
|
* from datasource class
|
317
|
* we get the datasource type form the inverted map
|
318
|
* */
|
319
|
r.setDatasourceType(getRepositoryType(r.getDatasourceClass()));
|
320
|
r.setInterfaces(this.getRepositoryInterface(r.getId()));
|
321
|
r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
|
322
|
r.setCountryName(getCountryName(r.getCountryCode()));
|
323
|
return r;
|
324
|
}
|
325
|
|
326
|
|
327
|
private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
|
328
|
|
329
|
List<Repository> reps = new ArrayList<>();
|
330
|
for (Repository r : rs) {
|
331
|
if (r.getCollectedFrom() != null && r.getCollectedFrom().equals(mode))
|
332
|
reps.add(r);
|
333
|
|
334
|
}
|
335
|
return reps;
|
336
|
}
|
337
|
|
338
|
@Override
|
339
|
public List<Repository> getRepositoriesOfUser(String page, String size) throws JSONException {
|
340
|
String userEmail = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail();
|
341
|
LOGGER.debug("Retreiving repositories of authenticated user : " + userEmail);
|
342
|
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles());
|
343
|
return getRepositories(new ArrayList<>(repoIds));
|
344
|
}
|
345
|
|
346
|
@Override
|
347
|
public List<Repository> getRepositoriesOfUser(String userEmail, String page, String size) throws JSONException {
|
348
|
LOGGER.debug("Retreiving repositories of authenticated user : " + userEmail);
|
349
|
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles(userEmail));
|
350
|
return getRepositories(new ArrayList<>(repoIds));
|
351
|
}
|
352
|
|
353
|
@Override
|
354
|
public List<RepositorySnippet> getRepositoriesSnippetOfUser(String page, String size) throws Exception {
|
355
|
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles());
|
356
|
return getRepositoriesSnippets(new ArrayList<>(repoIds));
|
357
|
}
|
358
|
|
359
|
@Override
|
360
|
public List<RepositorySnippet> getRepositoriesSnippetOfUser(String userEmail, String page, String size) throws Exception {
|
361
|
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles(userEmail));
|
362
|
return getRepositoriesSnippets(new ArrayList<>(repoIds));
|
363
|
}
|
364
|
|
365
|
@Override
|
366
|
public RepositorySnippet getRepositorySnippetById(String id) throws JSONException, ResourceNotFoundException {
|
367
|
|
368
|
LOGGER.debug("Retreiving repositories with id : " + id);
|
369
|
RepositorySnippet repo = null;
|
370
|
UriComponents uriComponents = searchSnipperDatasource("0", "100");
|
371
|
RequestFilter requestFilter = new RequestFilter();
|
372
|
requestFilter.setId(id);
|
373
|
|
374
|
try {
|
375
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
376
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
377
|
|
378
|
if (jsonArray.length() == 0)
|
379
|
throw new ResourceNotFoundException();
|
380
|
|
381
|
repo = Converter.jsonToRepositorySnippetObject(jsonArray.getJSONObject(0));
|
382
|
return repo;
|
383
|
} catch (JSONException e) {
|
384
|
LOGGER.debug("Exception on getRepositoryById", e);
|
385
|
emailUtils.reportException(e);
|
386
|
throw e;
|
387
|
}
|
388
|
|
389
|
}
|
390
|
|
391
|
@Override
|
392
|
public Repository getRepositoryById(String id) throws JSONException, ResourceNotFoundException {
|
393
|
|
394
|
LOGGER.debug("Retreiving repositories with id : " + id);
|
395
|
Repository repo = null;
|
396
|
UriComponents uriComponents = searchDatasource("0", "100");
|
397
|
RequestFilter requestFilter = new RequestFilter();
|
398
|
requestFilter.setId(id);
|
399
|
|
400
|
try {
|
401
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
402
|
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
403
|
|
404
|
if (jsonArray.length() == 0)
|
405
|
throw new ResourceNotFoundException();
|
406
|
|
407
|
repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
|
408
|
return updateRepositoryInfo(repo);
|
409
|
} catch (JSONException e) {
|
410
|
LOGGER.debug("Exception on getRepositoryById", e);
|
411
|
emailUtils.reportException(e);
|
412
|
throw e;
|
413
|
}
|
414
|
|
415
|
}
|
416
|
|
417
|
|
418
|
@Override
|
419
|
public List<AggregationDetails> getRepositoryAggregations(String id, int from, int size) throws JSONException {
|
420
|
|
421
|
LOGGER.debug("Retreiving aggregations for repository with id : " + id);
|
422
|
UriComponents uriComponents = searchDatasource(from + "", size + "");
|
423
|
RequestFilter requestFilter = new RequestFilter();
|
424
|
requestFilter.setId(id);
|
425
|
|
426
|
List<AggregationDetails> aggregationHistory = new ArrayList<>();
|
427
|
|
428
|
try {
|
429
|
long start = System.currentTimeMillis();
|
430
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
431
|
long end = System.currentTimeMillis();
|
432
|
|
433
|
System.out.println("Aggregations request through rest template took " + (end - start) + "ms");
|
434
|
JSONObject repository = new JSONObject(rs);
|
435
|
|
436
|
if (repository.getJSONArray("datasourceInfo").length() == 0)
|
437
|
return aggregationHistory;
|
438
|
|
439
|
start = System.currentTimeMillis();
|
440
|
aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
|
441
|
end = System.currentTimeMillis();
|
442
|
|
443
|
System.out.println("Getting aggregations history from json " + (end - start) + "ms");
|
444
|
return aggregationHistory.size() == 0 ? aggregationHistory : aggregationHistory.stream()
|
445
|
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
446
|
.limit(size)
|
447
|
.collect(Collectors.toList());
|
448
|
} catch (JSONException e) {
|
449
|
LOGGER.debug("Exception on getRepositoryAggregations", e);
|
450
|
emailUtils.reportException(e);
|
451
|
throw e;
|
452
|
}
|
453
|
|
454
|
}
|
455
|
|
456
|
@Override
|
457
|
public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(String id) throws JSONException {
|
458
|
LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id);
|
459
|
UriComponents uriComponents = searchDatasource("0", "100");
|
460
|
RequestFilter requestFilter = new RequestFilter();
|
461
|
requestFilter.setId(id);
|
462
|
|
463
|
List<AggregationDetails> aggregationHistory = new ArrayList<>();
|
464
|
Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
|
465
|
try {
|
466
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
467
|
JSONObject repository = new JSONObject(rs);
|
468
|
|
469
|
if (repository.getJSONArray("datasourceInfo").length() == 0)
|
470
|
return aggregationByYear;
|
471
|
|
472
|
aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
|
473
|
return aggregationHistory.size() == 0 ? aggregationByYear : createYearMap(aggregationHistory);
|
474
|
|
475
|
} catch (JSONException e) {
|
476
|
LOGGER.debug("Exception on getRepositoryAggregations", e);
|
477
|
emailUtils.reportException(e);
|
478
|
throw e;
|
479
|
}
|
480
|
}
|
481
|
|
482
|
private Map<String, List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
|
483
|
Map<String, List<AggregationDetails>> aggregationByYear;
|
484
|
aggregationHistory = aggregationHistory.stream()
|
485
|
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
486
|
.collect(Collectors.toList());
|
487
|
|
488
|
return aggregationHistory.stream()
|
489
|
.collect(Collectors.groupingBy(AggregationDetails::getYear));
|
490
|
}
|
491
|
|
492
|
|
493
|
@Override
|
494
|
public List<Repository> getRepositoriesByName(String name,
|
495
|
String page,
|
496
|
String size) throws JSONException {
|
497
|
|
498
|
LOGGER.debug("Retreiving repositories with official name : " + name);
|
499
|
UriComponents uriComponents = searchDatasource("0", "100");
|
500
|
RequestFilter requestFilter = new RequestFilter();
|
501
|
requestFilter.setOfficialname(name);
|
502
|
|
503
|
try {
|
504
|
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
505
|
List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
|
506
|
for (Repository r : repos)
|
507
|
updateRepositoryInfo(r);
|
508
|
return repos;
|
509
|
} catch (Exception e) {
|
510
|
LOGGER.debug("Exception on getRepositoriesByName", e);
|
511
|
emailUtils.reportException(e);
|
512
|
throw e;
|
513
|
}
|
514
|
|
515
|
}
|
516
|
|
517
|
@Override
|
518
|
public List<RepositoryInterface> getRepositoryInterface(String id) throws JSONException {
|
519
|
|
520
|
UriComponents uriComponents = UriComponentsBuilder
|
521
|
.fromHttpUrl(baseAddress + "/ds/api/")
|
522
|
.path("/{id}")
|
523
|
.build().expand(id).encode();
|
524
|
|
525
|
try {
|
526
|
String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
|
527
|
return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
|
528
|
} catch (Exception e) {
|
529
|
LOGGER.debug("Exception on getRepositoryInterface", e);
|
530
|
emailUtils.reportException(e);
|
531
|
throw e;
|
532
|
}
|
533
|
|
534
|
}
|
535
|
|
536
|
@Override
|
537
|
public Repository addRepository(String datatype,
|
538
|
Repository repository) throws Exception {
|
539
|
|
540
|
LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
|
541
|
|
542
|
repository.setCountryCode(countriesMap.get(repository.getCountryName()));
|
543
|
repository.setActivationId(UUID.randomUUID().toString());
|
544
|
repository.setCollectedFrom("infrastruct_::openaire");
|
545
|
|
546
|
if (datatype.equals("journal")) {
|
547
|
repository.setId("openaire____::issn" + repository.getIssn());
|
548
|
repository.setNamespacePrefix("issn" + repository.getIssn());
|
549
|
this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
|
550
|
} else if (datatype.equals("aggregator")) {
|
551
|
repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
|
552
|
repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0, 12));
|
553
|
this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
|
554
|
} else {
|
555
|
this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication());
|
556
|
}
|
557
|
|
558
|
// TODO: move the following code elsewhere (creation and assignment of role to user) ??
|
559
|
// Create new role
|
560
|
String newRoleName = roleMappingService.getRoleIdByRepoId(repository.getId());
|
561
|
Role newRole = new Role(newRoleName, repository.getOfficialName());
|
562
|
Integer couId = null;
|
563
|
try {
|
564
|
couId = registryCalls.createRole(newRole);
|
565
|
} catch (HttpClientErrorException e) {
|
566
|
couId = registryCalls.getCouId(newRoleName);
|
567
|
if (couId == null) {
|
568
|
LOGGER.error(String.format("Could not create role '%s'", newRoleName), e);
|
569
|
}
|
570
|
} catch (Exception e) {
|
571
|
LOGGER.error(String.format("Could not create role '%s'", newRoleName), e);
|
572
|
throw e;
|
573
|
}
|
574
|
|
575
|
// Assign new role to the user that created it
|
576
|
Integer coPersonId = registryCalls.getCoPersonIdByIdentifier();
|
577
|
if (couId != null) {
|
578
|
Integer role = registryCalls.getRoleId(coPersonId, couId);
|
579
|
try {
|
580
|
registryCalls.assignMemberRole(coPersonId, couId, role);
|
581
|
|
582
|
// Add role to current user authorities
|
583
|
authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(repository.getId()));
|
584
|
} catch (Exception e) {
|
585
|
LOGGER.debug("Exception on assign role to user during add repository", e);
|
586
|
throw e;
|
587
|
}
|
588
|
|
589
|
}
|
590
|
|
591
|
|
592
|
return repository;
|
593
|
}
|
594
|
|
595
|
/* update method acting as add -> send email with registration topic/body*/
|
596
|
private Repository latentUpdate(Repository repository, Authentication authentication) throws Exception {
|
597
|
UriComponents uriComponents = UriComponentsBuilder
|
598
|
.fromHttpUrl(baseAddress + "/ds/update/")
|
599
|
.build()
|
600
|
.encode();
|
601
|
|
602
|
try {
|
603
|
String json_repository = Converter.repositoryObjectToJson(repository);
|
604
|
LOGGER.debug("JSON to add(update) -> " + json_repository);
|
605
|
|
606
|
HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
|
607
|
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class);
|
608
|
|
609
|
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
610
|
// emailUtils.sendUserRegistrationEmail(repository, authentication);
|
611
|
// emailUtils.sendAdminRegistrationEmail(repository, authentication);
|
612
|
} else
|
613
|
LOGGER.debug(responseEntity.getBody().toString());
|
614
|
|
615
|
return repository;
|
616
|
} catch (Exception e) {
|
617
|
LOGGER.debug("Exception on updateRepository", e);
|
618
|
emailUtils.reportException(e);
|
619
|
throw e;
|
620
|
}
|
621
|
|
622
|
|
623
|
}
|
624
|
|
625
|
@Override
|
626
|
public Repository updateRepository(Repository repository, Authentication authentication) throws Exception {
|
627
|
UriComponents uriComponents = UriComponentsBuilder
|
628
|
.fromHttpUrl(baseAddress + "/ds/update/")
|
629
|
.build()
|
630
|
.encode();
|
631
|
|
632
|
try {
|
633
|
String json_repository = Converter.repositoryObjectToJson(repository);
|
634
|
|
635
|
LOGGER.debug("JSON to update -> " + json_repository);
|
636
|
|
637
|
HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
|
638
|
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity
|
639
|
, ResponseEntity.class);
|
640
|
|
641
|
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
642
|
emailUtils.sendUserUpdateRepositoryInfoEmail(repository, authentication);
|
643
|
emailUtils.sendAdminUpdateRepositoryInfoEmail(repository, authentication);
|
644
|
} else
|
645
|
LOGGER.debug(responseEntity.getBody().toString());
|
646
|
|
647
|
return repository;
|
648
|
} catch (Exception e) {
|
649
|
LOGGER.debug("Exception on updateRepository", e);
|
650
|
emailUtils.reportException(e);
|
651
|
throw e;
|
652
|
}
|
653
|
}
|
654
|
|
655
|
private void storeRepository(Repository repository, Authentication authentication) throws Exception {
|
656
|
|
657
|
Date utilDate = new Date();
|
658
|
Timestamp date = new Timestamp(utilDate.getTime());
|
659
|
repository.setDateOfCollection(date);
|
660
|
repository.setAggregator("OPENAIRE");
|
661
|
repository.setCountryCode(countriesMap.get(repository.getCountryName()));
|
662
|
|
663
|
UriComponents uriComponents = UriComponentsBuilder
|
664
|
.fromHttpUrl(baseAddress + "/ds/add/")
|
665
|
.build()
|
666
|
.encode();
|
667
|
String json_repository = Converter.repositoryObjectToJson(repository);
|
668
|
HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
|
669
|
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class);
|
670
|
|
671
|
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
672
|
emailUtils.sendUserRegistrationEmail(repository, authentication);
|
673
|
emailUtils.sendAdminRegistrationEmail(repository, authentication);
|
674
|
} else {
|
675
|
LOGGER.debug(responseEntity.getBody().toString());
|
676
|
}
|
677
|
}
|
678
|
|
679
|
@Override
|
680
|
public void deleteRepositoryInterface(String id,
|
681
|
String registeredBy) {
|
682
|
UriComponents uriComponents = UriComponentsBuilder
|
683
|
.fromHttpUrl(baseAddress + "/ds/api/")
|
684
|
.path("/{id}")
|
685
|
.build().expand(id).encode();
|
686
|
LOGGER.debug(uriComponents.toUri());
|
687
|
restTemplate.delete(uriComponents.toUri());
|
688
|
}
|
689
|
|
690
|
@Override
|
691
|
public RepositoryInterface addRepositoryInterface(String datatype,
|
692
|
String repoId,
|
693
|
String registeredBy,
|
694
|
String comment, RepositoryInterface repositoryInterface) throws Exception {
|
695
|
try {
|
696
|
Repository e = this.getRepositoryById(repoId);
|
697
|
repositoryInterface = createRepositoryInterface(e, repositoryInterface, datatype);
|
698
|
String json_interface = Converter.repositoryInterfaceObjectToJson(e, repositoryInterface);
|
699
|
|
700
|
UriComponents uriComponents = UriComponentsBuilder
|
701
|
.fromHttpUrl(baseAddress + "/ds/api/add/")
|
702
|
.build()
|
703
|
.encode();
|
704
|
|
705
|
HttpEntity<String> httpEntity = new HttpEntity<>(json_interface, httpHeaders);
|
706
|
|
707
|
restTemplate.postForObject(uriComponents.toUri(), httpEntity, String.class);
|
708
|
|
709
|
emailUtils.sendAdminRegisterInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
710
|
emailUtils.sendUserRegisterInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
711
|
|
712
|
submitInterfaceValidation(e, registeredBy, repositoryInterface, false);
|
713
|
|
714
|
return repositoryInterface;
|
715
|
|
716
|
} catch (Exception e) {
|
717
|
LOGGER.error("Exception on addRepositoryInterface", e);
|
718
|
emailUtils.reportException(e);
|
719
|
throw e;
|
720
|
}
|
721
|
}
|
722
|
|
723
|
@Override
|
724
|
public RepositoryInterface updateRepositoryInterface(String repoId,
|
725
|
String registeredBy,
|
726
|
String comment, RepositoryInterface repositoryInterface) throws Exception {
|
727
|
|
728
|
this.updateBaseUrl(repoId, repositoryInterface.getId(), repositoryInterface.getBaseUrl());
|
729
|
this.updateCompliance(repoId, repositoryInterface.getId(), repositoryInterface.getCompliance());
|
730
|
this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet());
|
731
|
|
732
|
Repository repository = this.getRepositoryById(repoId);
|
733
|
try {
|
734
|
emailUtils.sendAdminUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
735
|
emailUtils.sendUserUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
736
|
} catch (Exception e) {
|
737
|
LOGGER.warn("Could not send emails", e);
|
738
|
}
|
739
|
|
740
|
submitInterfaceValidation(getRepositoryById(repoId), registeredBy, repositoryInterface, true);
|
741
|
|
742
|
return repositoryInterface;
|
743
|
}
|
744
|
|
745
|
private void submitInterfaceValidation(Repository repo, String userEmail, RepositoryInterface iFace, boolean updateExisting) throws ValidatorServiceException {
|
746
|
JobForValidation job = new JobForValidation();
|
747
|
|
748
|
job.setActivationId(UUID.randomUUID().toString());
|
749
|
job.setAdminEmails(Collections.singletonList(this.adminEmail));
|
750
|
job.setBaseUrl(iFace.getBaseUrl());
|
751
|
job.setDatasourceId(repo.getId());
|
752
|
job.setDesiredCompatibilityLevel(iFace.getDesiredCompatibilityLevel());
|
753
|
job.setInterfaceId(iFace.getId());
|
754
|
job.setOfficialName(repo.getOfficialName());
|
755
|
job.setRepoType(repo.getDatasourceType());
|
756
|
job.setUserEmail(userEmail);
|
757
|
job.setValidationSet((iFace.getAccessSet().isEmpty() ? "none" : iFace.getAccessSet()));
|
758
|
job.setRecords(-1);
|
759
|
job.setRegistration(!updateExisting);
|
760
|
job.setUpdateExisting(updateExisting);
|
761
|
|
762
|
this.validatorService.submitJobForValidation(job);
|
763
|
}
|
764
|
|
765
|
private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
|
766
|
|
767
|
iFace.setContentDescription("metadata");
|
768
|
iFace.setCompliance("UNKNOWN");
|
769
|
|
770
|
if (datatype.equals("re3data"))
|
771
|
iFace.setAccessFormat("oai_datacite");
|
772
|
else
|
773
|
iFace.setAccessFormat("oai_dc");
|
774
|
|
775
|
|
776
|
if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty())
|
777
|
iFace.setTypology(repo.getDatasourceClass());
|
778
|
else if (datatype.equalsIgnoreCase("journal"))
|
779
|
iFace.setTypology("pubsrepository::journal");
|
780
|
else if (datatype.equalsIgnoreCase("aggregator"))
|
781
|
iFace.setTypology("aggregator::pubsrepository::unknown");
|
782
|
else if (datatype.equalsIgnoreCase("opendoar"))
|
783
|
iFace.setTypology("pubsrepository::unknown");
|
784
|
else if (datatype.equalsIgnoreCase("re3data"))
|
785
|
iFace.setTypology("datarepository::unknown");
|
786
|
|
787
|
iFace.setRemovable(true);
|
788
|
iFace.setAccessProtocol("oai");
|
789
|
iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
|
790
|
iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
|
791
|
if (iFace.getAccessSet() == null || iFace.getAccessSet().isEmpty()) {
|
792
|
LOGGER.debug("set is empty: " + iFace.getAccessSet());
|
793
|
iFace.removeAccessSet();
|
794
|
iFace.setAccessSet("none");
|
795
|
}
|
796
|
return iFace;
|
797
|
}
|
798
|
|
799
|
@Override
|
800
|
public List<String> getDnetCountries() {
|
801
|
LOGGER.debug("Getting dnet-countries!");
|
802
|
return Converter.readFile("countries.txt");
|
803
|
}
|
804
|
|
805
|
@Override
|
806
|
public List<String> getTypologies() {
|
807
|
return Converter.readFile("typologies.txt");
|
808
|
}
|
809
|
|
810
|
@Override
|
811
|
public List<Timezone> getTimezones() {
|
812
|
List<String> timezones = Converter.readFile("timezones.txt");
|
813
|
return Converter.toTimezones(timezones);
|
814
|
}
|
815
|
|
816
|
@Override
|
817
|
public List<String> getUrlsOfUserRepos(String userEmail,
|
818
|
String page,
|
819
|
String size) {
|
820
|
UriComponents uriComponents = UriComponentsBuilder
|
821
|
.fromHttpUrl(baseAddress + "/api/baseurl/")
|
822
|
.path("/{page}/{size}")
|
823
|
.build().expand(page, size).encode();
|
824
|
|
825
|
try {
|
826
|
RequestFilter requestFilter = new RequestFilter();
|
827
|
requestFilter.setRegisteredby(userEmail);
|
828
|
return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(), requestFilter, String[].class));
|
829
|
} catch (Exception e) {
|
830
|
LOGGER.debug("Exception on addRepositoryInterface", e);
|
831
|
emailUtils.reportException(e);
|
832
|
throw e;
|
833
|
}
|
834
|
}
|
835
|
|
836
|
@Override
|
837
|
public List<String> getDatasourceVocabularies(String mode) {
|
838
|
|
839
|
List<String> resultSet = new ArrayList<>();
|
840
|
for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
|
841
|
if (mode.equalsIgnoreCase("aggregator")) {
|
842
|
if (entry.getKey().contains("aggregator"))
|
843
|
resultSet.add(entry.getValue());
|
844
|
} else if (mode.equalsIgnoreCase("journal")) {
|
845
|
if (entry.getKey().contains("journal"))
|
846
|
resultSet.add(entry.getValue());
|
847
|
} else if (mode.equalsIgnoreCase("opendoar")) {
|
848
|
if (entry.getKey().contains("pubsrepository"))
|
849
|
resultSet.add(entry.getValue());
|
850
|
} else if (mode.equalsIgnoreCase("re3data")) {
|
851
|
if (entry.getKey().contains("datarepository"))
|
852
|
resultSet.add(entry.getValue());
|
853
|
}
|
854
|
}
|
855
|
|
856
|
|
857
|
return resultSet;
|
858
|
}
|
859
|
|
860
|
private Vocabulary getVocabulary(String vocName) {
|
861
|
|
862
|
if (!vocabularyMap.containsKey(vocName)) {
|
863
|
vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
|
864
|
}
|
865
|
return vocabularyMap.get(vocName);
|
866
|
}
|
867
|
|
868
|
|
869
|
@Override
|
870
|
public Map<String, String> getCompatibilityClasses(String mode) {
|
871
|
|
872
|
LOGGER.debug("Getting compatibility classes for mode: " + mode);
|
873
|
Map<String, String> retMap = new HashMap<String, String>();
|
874
|
|
875
|
Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
|
876
|
boolean foundData = false;
|
877
|
for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
|
878
|
if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
|
879
|
return compatibilityClasses;
|
880
|
else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
|
881
|
if (entry.getKey().matches("^openaire[1-9].0_data$")) {
|
882
|
retMap.put(entry.getKey(), entry.getValue());
|
883
|
foundData = true;
|
884
|
}
|
885
|
} else {
|
886
|
if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
|
887
|
retMap.put(entry.getKey(), entry.getValue());
|
888
|
}
|
889
|
}
|
890
|
|
891
|
//TODO TO BE REMOVED WHEN VOCABULARIES ARE UPDATED
|
892
|
if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA) && !foundData)
|
893
|
retMap.put("openaire2.0_data", "OpenAIRE Data (funded, referenced datasets)");
|
894
|
|
895
|
return retMap;
|
896
|
}
|
897
|
|
898
|
@Override
|
899
|
public Map<String, String> getDatasourceClasses(String mode) {
|
900
|
|
901
|
LOGGER.debug("Getting datasource classes for mode: " + mode);
|
902
|
|
903
|
Map<String, String> retMap = new HashMap<String, String>();
|
904
|
|
905
|
for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
|
906
|
if (mode.equalsIgnoreCase("aggregator")) {
|
907
|
if (entry.getKey().contains("aggregator"))
|
908
|
retMap.put(entry.getKey(), entry.getValue());
|
909
|
} else if (mode.equalsIgnoreCase("journal")) {
|
910
|
if (entry.getKey().contains("journal"))
|
911
|
retMap.put(entry.getKey(), entry.getValue());
|
912
|
} else if (mode.equalsIgnoreCase("opendoar")) {
|
913
|
if (entry.getKey().contains("pubsrepository"))
|
914
|
retMap.put(entry.getKey(), entry.getValue());
|
915
|
} else if (mode.equalsIgnoreCase("re3data")) {
|
916
|
if (entry.getKey().contains("datarepository"))
|
917
|
retMap.put(entry.getKey(), entry.getValue());
|
918
|
}
|
919
|
}
|
920
|
return filterResults(retMap, mode);
|
921
|
|
922
|
}
|
923
|
|
924
|
private Map<String, String> filterResults(Map<String, String> map, String mode) {
|
925
|
|
926
|
HashMap<String, String> filteredMap = new HashMap<>();
|
927
|
for (String key : map.keySet())
|
928
|
if (dataSourceClass.get(mode).contains(key))
|
929
|
filteredMap.put(key, map.get(key));
|
930
|
|
931
|
return filteredMap;
|
932
|
}
|
933
|
|
934
|
@Override
|
935
|
public String getCountryName(String countryCode) {
|
936
|
return inverseCountriesMap.get(countryCode);
|
937
|
}
|
938
|
|
939
|
@Override
|
940
|
public MetricsInfo getMetricsInfoForRepository(String repoId) throws RepositoryServiceException {
|
941
|
try {
|
942
|
|
943
|
MetricsInfo metricsInfo = new MetricsInfo();
|
944
|
metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
|
945
|
metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
|
946
|
return metricsInfo;
|
947
|
|
948
|
} catch (Exception e) {
|
949
|
LOGGER.error("Error while getting metrics info for repository: ", e);
|
950
|
emailUtils.reportException(e);
|
951
|
throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
|
952
|
}
|
953
|
}
|
954
|
|
955
|
@Override
|
956
|
public Map<String, String> getListLatestUpdate(String mode) throws JSONException {
|
957
|
if (mode.equals("opendoar"))
|
958
|
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::" + mode).get(0).getLastCollectionDate());
|
959
|
else
|
960
|
/*
|
961
|
* first api of re3data has null value on collection date
|
962
|
* */
|
963
|
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::" + mode).get(1).getLastCollectionDate());
|
964
|
}
|
965
|
|
966
|
private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) throws Exception {
|
967
|
UriComponents uriComponents = UriComponentsBuilder
|
968
|
.fromHttpUrl(baseAddress + "/ds/api/oaiset")
|
969
|
.queryParam("dsId", repositoryId)
|
970
|
.queryParam("apiId", repositoryInterfaceId)
|
971
|
.queryParam("oaiSet", validationSet)
|
972
|
.build().encode();
|
973
|
restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, null, ResponseEntity.class);
|
974
|
|
975
|
}
|
976
|
|
977
|
|
978
|
private void updateBaseUrl(String repositoryId, String repositoryInterfaceId, String baseUrl) {
|
979
|
UriComponents uriComponents = UriComponentsBuilder
|
980
|
.fromHttpUrl(baseAddress + "/ds/api/baseurl")
|
981
|
.queryParam("dsId", repositoryId)
|
982
|
.queryParam("apiId", repositoryInterfaceId)
|
983
|
.queryParam("baseUrl", baseUrl)
|
984
|
.build().encode();
|
985
|
restTemplate.postForObject(uriComponents.toUri(), null, String.class);
|
986
|
}
|
987
|
|
988
|
private void updateCompliance(String repositoryId, String repositoryInterfaceId, String compliance) {
|
989
|
UriComponents uriComponents = UriComponentsBuilder
|
990
|
.fromHttpUrl(baseAddress + "/ds/api/compliance")
|
991
|
.queryParam("dsId", repositoryId)
|
992
|
.queryParam("apiId", repositoryInterfaceId)
|
993
|
.queryParam("compliance", compliance)
|
994
|
.build().encode();
|
995
|
restTemplate.postForObject(uriComponents.toUri(), null, String.class);
|
996
|
}
|
997
|
|
998
|
private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
|
999
|
|
1000
|
//build the uri params
|
1001
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
|
1002
|
|
1003
|
//create new template engine
|
1004
|
RestTemplate template = new RestTemplate();
|
1005
|
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
|
1006
|
ResponseEntity<MetricsNumbers> resp;
|
1007
|
try {
|
1008
|
//communicate with endpoint
|
1009
|
resp = template.exchange(
|
1010
|
builder.build().encode().toUri(),
|
1011
|
HttpMethod.GET,
|
1012
|
null,
|
1013
|
new ParameterizedTypeReference<MetricsNumbers>() {
|
1014
|
});
|
1015
|
} catch (RestClientException e) {
|
1016
|
LOGGER.debug("Exception on getMetricsNumbers", e);
|
1017
|
emailUtils.reportException(e);
|
1018
|
throw e;
|
1019
|
}
|
1020
|
|
1021
|
return resp.getBody();
|
1022
|
}
|
1023
|
|
1024
|
private String getOpenAIREId(String repoId) {
|
1025
|
|
1026
|
if (repoId != null && repoId.contains("::")) {
|
1027
|
return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
|
1028
|
}
|
1029
|
|
1030
|
return null;
|
1031
|
}
|
1032
|
|
1033
|
private UriComponents searchDatasource(String page, String size) {
|
1034
|
|
1035
|
return UriComponentsBuilder
|
1036
|
.fromHttpUrl(baseAddress + "/ds/search/")
|
1037
|
.path("/{page}/{size}/")
|
1038
|
.queryParam("requestSortBy", "officialname")
|
1039
|
.queryParam("order", "ASCENDING")
|
1040
|
.build().expand(page, size).encode();
|
1041
|
}
|
1042
|
|
1043
|
private UriComponents searchSnipperDatasource(String page, String size) {
|
1044
|
|
1045
|
return UriComponentsBuilder
|
1046
|
.fromHttpUrl(baseAddress + "/ds/searchsnippet/")
|
1047
|
.path("/{page}/{size}/")
|
1048
|
.queryParam("requestSortBy", "officialname")
|
1049
|
.queryParam("order", "ASCENDING")
|
1050
|
.build().expand(page, size).encode();
|
1051
|
}
|
1052
|
|
1053
|
private UriComponents searchRegisteredDatasource(String requestSortBy, String order, String page, String size) {
|
1054
|
|
1055
|
return UriComponentsBuilder
|
1056
|
.fromHttpUrl(baseAddress + "/ds/searchregistered/")
|
1057
|
.path("/{page}/{size}/")
|
1058
|
.queryParam("requestSortBy", requestSortBy)
|
1059
|
.queryParam("order", order)
|
1060
|
.build().expand(page, size).encode();
|
1061
|
}
|
1062
|
|
1063
|
private String getRepositoryType(String typology) {
|
1064
|
return invertedDataSourceClass.get(typology);
|
1065
|
}
|
1066
|
|
1067
|
private List<String> getRoleIdsFromUserRoles(String userEmail) {
|
1068
|
Integer coPersonId = registryCalls.getCoPersonIdByEmail(userEmail);
|
1069
|
JsonArray roles;
|
1070
|
ArrayList<String> roleIds = new ArrayList<>();
|
1071
|
ArrayList<Integer> couIds = new ArrayList<>();
|
1072
|
if (coPersonId != null) {
|
1073
|
roles = registryCalls.getRolesWithStatus(coPersonId, AaiRegistryService.RoleStatus.ACTIVE);
|
1074
|
for (JsonElement role : roles) {
|
1075
|
JsonObject object = role.getAsJsonObject();
|
1076
|
if (object.get("CouId") == null) {
|
1077
|
continue;
|
1078
|
}
|
1079
|
couIds.add(object.get("CouId").getAsInt());
|
1080
|
}
|
1081
|
|
1082
|
roleIds.addAll(registryCalls.getCouNames(couIds).values());
|
1083
|
|
1084
|
}
|
1085
|
return roleIds;
|
1086
|
}
|
1087
|
|
1088
|
private List<String> getRepoIdsFromUserRoles(String userEmail) {
|
1089
|
List<String> roleIds = getRoleIdsFromUserRoles(userEmail);
|
1090
|
List<String> repoIds = new ArrayList<>();
|
1091
|
for (String role : roleIds) {
|
1092
|
if (role.contains("datasource")) {
|
1093
|
// TODO: ask if checking for BETA prefix is required
|
1094
|
repoIds.add(role.replaceFirst(".*datasource\\.", "").replace("$", ":"));
|
1095
|
}
|
1096
|
}
|
1097
|
return repoIds;
|
1098
|
}
|
1099
|
}
|