Project

General

Profile

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.api.functionality.ValidatorServiceException;
7
import eu.dnetlib.domain.data.Repository;
8
import eu.dnetlib.domain.data.RepositoryInterface;
9
import eu.dnetlib.domain.enabling.Vocabulary;
10
import eu.dnetlib.domain.functionality.validator.JobForValidation;
11
import eu.dnetlib.repo.manager.domain.RepositorySnippet;
12
import eu.dnetlib.repo.manager.domain.RequestFilter;
13
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
14
import eu.dnetlib.repo.manager.shared.*;
15
import eu.dnetlib.repo.manager.utils.Converter;
16
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
17
import gr.uoa.di.driver.xml.repository.INTERFACE;
18
import org.apache.commons.codec.digest.DigestUtils;
19
import org.apache.log4j.Logger;
20
import org.json.JSONArray;
21
import org.json.JSONException;
22
import org.json.JSONObject;
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.beans.factory.annotation.Value;
25
import org.springframework.core.ParameterizedTypeReference;
26
import org.springframework.http.*;
27
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
28
import org.springframework.security.core.Authentication;
29
import org.springframework.security.core.context.SecurityContextHolder;
30
import org.springframework.stereotype.Service;
31
import org.springframework.web.bind.annotation.PathVariable;
32
import org.springframework.web.bind.annotation.RequestBody;
33
import org.springframework.web.bind.annotation.RequestParam;
34
import org.springframework.web.client.RestClientException;
35
import org.springframework.web.client.RestTemplate;
36
import org.springframework.web.util.UriComponents;
37
import org.springframework.web.util.UriComponentsBuilder;
38

    
39
import javax.annotation.PostConstruct;
40
import java.io.IOException;
41
import java.sql.Timestamp;
42
import java.util.*;
43
import java.util.concurrent.ConcurrentHashMap;
44
import java.util.stream.Collectors;
45

    
46
@Service("repositoryService")
47
public class RepositoryServiceImpl implements RepositoryService {
48

    
49
    @Value("${api.baseAddress}")
50
    private String baseAddress;
51

    
52
    @Value("${services.repo-manager.adminEmail}")
53
    private String adminEmail;
54

    
55
    @Autowired
56
    RestTemplate restTemplate;
57

    
58
    private HttpHeaders httpHeaders;
59

    
60
    private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
61

    
62
    private static final Logger LOGGER = Logger.getLogger(RepositoryServiceImpl.class);
63

    
64
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
65
    private String usageStatisticsDiagramsBaseURL;
66

    
67
    @Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
68
    private String usageStatisticsNumbersBaseURL;
69

    
70
    @Autowired
71
    private VocabularyLoader vocabularyLoader;
72

    
73
    @Autowired
74
    private PiWikService piWikService;
75

    
76
    @Autowired
77
    private EmailUtils emailUtils;
78

    
79
    @Autowired
80
    ValidatorService validatorService;
81

    
82

    
83
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<>();
84

    
85
    private Map<String, String> countriesMap = new HashMap<>();
86
    private Map<String, String> inverseCountriesMap = new HashMap<>();
87

    
88
    private static Map<String,List<String>> dataSourceClass = new HashMap<>();
89

    
90
    private static Map<String,String> invertedDataSourceClass = new HashMap<>();
91

    
92

    
93

    
94
    @PostConstruct
95
    private void init() {
96
        LOGGER.debug("Initialization method of repository api!");
97
        LOGGER.debug("Updated version!");
98

    
99
        dataSourceClass.put("opendoar",Arrays.asList("pubsrepository::institutional","pubsrepository::thematic","pubsrepository::unknown","pubsrepository::mock"));
100
        dataSourceClass.put("re3data", Collections.singletonList("datarepository::unknown"));
101
        dataSourceClass.put("journal", Collections.singletonList("pubsrepository::journal"));
102
        dataSourceClass.put("aggregator",Arrays.asList("aggregator::pubsrepository::institutional","aggregator::pubsrepository::journals","aggregator::datarepository", "aggregator::pubsrepository::unknown"));
103

    
104
        invertedDataSourceClass.put("pubsrepository::institutional","opendoar");
105
        invertedDataSourceClass.put("pubsrepository::thematic","opendoar");
106
        invertedDataSourceClass.put("pubsrepository::unknown","opendoar");
107
        invertedDataSourceClass.put("pubsrepository::mock","opendoar");
108
        invertedDataSourceClass.put("datarepository::unknown","re3data");
109
        invertedDataSourceClass.put("pubsrepository::journal","journal");
110
        invertedDataSourceClass.put("aggregator::pubsrepository::institutional","aggregator");
111
        invertedDataSourceClass.put("aggregator::pubsrepository::journals","aggregator");
112
        invertedDataSourceClass.put("aggregator::datarepository","aggregator");
113
        invertedDataSourceClass.put("aggregator::pubsrepository::unknown","aggregator");
114

    
115

    
116
        httpHeaders = new HttpHeaders();
117
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
118

    
119
        for (String vocName : vocabularyNames) {
120
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
121
        }
122

    
123
        Country[] countries = getCountries();
124
        for (Country c : countries) {
125
            countriesMap.put(c.getName(), c.getCode());
126
            inverseCountriesMap.put(c.getCode(), c.getName());
127
        }
128

    
129

    
130
    }
131

    
132
    @Override
133
    public Country[] getCountries() {
134
        UriComponents uriComponents = UriComponentsBuilder
135
                .fromHttpUrl(baseAddress + "/ds/countries")
136
                .build().encode();
137
        return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
138
    }
139

    
140

    
141
    @Override
142
    public List<RepositorySnippet> getRepositoriesByCountry(String country,
143
                                                            String mode,
144
                                                            Boolean managed) throws JSONException, IOException {
145

    
146
        LOGGER.debug("Getting repositories by country!");
147
        int page = 0;
148
        int size = 100;
149
        List<RepositorySnippet> resultSet = new ArrayList<>();
150
        ObjectMapper mapper = new ObjectMapper();
151

    
152
        String filterKey = "UNKNOWN";
153
        if (mode.equalsIgnoreCase("opendoar"))
154
            filterKey = "openaire____::opendoar";
155
        else if (mode.equalsIgnoreCase("re3data"))
156
            filterKey = "openaire____::re3data";
157

    
158

    
159
        LOGGER.debug("Country code equals : " + country);
160
        LOGGER.debug("Filter mode equals : " + filterKey);
161

    
162
        UriComponents uriComponents = searchSnipperDatasource(String.valueOf(page),String.valueOf(size));
163
        RequestFilter requestFilter = new RequestFilter();
164
        requestFilter.setCountry(country);
165
        requestFilter.setCollectedfrom(filterKey);
166

    
167
        try{
168
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
169
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
170
            while (jsonArray.length() > 0 ) {
171
                resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
172
                        mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
173
                page += 1;
174
                uriComponents = searchSnipperDatasource(String.valueOf(page),String.valueOf(size));
175
                rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
176
                jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
177
            }
178
            return resultSet;
179
        }catch (Exception e){
180
            LOGGER.debug("Exception on getRepositoriesByCountry" , e);
181
//            emailUtils.reportException(e);
182
            throw e;
183
        }
184
    }
185

    
186
    public List<RepositorySnippet> searchRegisteredRepositories(String country, String typology, String englishName,
187
            String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception {
188

    
189
        LOGGER.debug("Searching registered repositories");
190

    
191
        List<RepositorySnippet> resultSet = new ArrayList<>();
192
        ObjectMapper mapper = new ObjectMapper();
193

    
194
        UriComponents uriComponents = searchRegisteredDatasource(requestSortBy, order, Integer.toString(page), Integer.toString(pageSize));
195

    
196
        RequestFilter requestFilter = new RequestFilter();
197
        requestFilter.setCountry(country);
198
        requestFilter.setTypology(typology);
199
        requestFilter.setOfficialname(officialName);
200
        requestFilter.setEnglishname(englishName);
201

    
202
        try {
203
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
204
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
205

    
206
            resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),  mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
207

    
208
             return resultSet;
209
        }catch (Exception e){
210
            LOGGER.error("Error searching registered datasources" , e);
211
            throw e;
212
        }
213
    }
214

    
215
    private Repository updateRepositoryInfo(Repository r) throws JSONException {
216

    
217
        /*
218
        * from datasource class
219
        * we get the datasource type form the inverted map
220
        * */
221
        r.setDatasourceType(getRepositoryType(r.getDatasourceClass()));
222
        r.setInterfaces(this.getRepositoryInterface(r.getId()));
223
        r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
224
        r.setCountryName(getCountryName(r.getCountryCode()));
225
        return r;
226
    }
227

    
228

    
229
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
230

    
231
        List<Repository> reps = new ArrayList<>();
232
        for (Repository r : rs) {
233
            if (r.getCollectedFrom() != null && r.getCollectedFrom().equals(mode))
234
                reps.add(r);
235

    
236
        }
237
        return reps;
238
    }
239

    
240
    @Override
241
    public List<Repository> getRepositoriesOfUser(String userEmail,
242
                                                  String page,
243
                                                  String size) throws JSONException {
244

    
245
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
246
        UriComponents uriComponents = searchDatasource(page,size);
247
        RequestFilter requestFilter = new RequestFilter();
248
        requestFilter.setRegisteredby(userEmail);
249

    
250
        try{
251
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
252

    
253
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
254
            for (Repository r : repos)
255
                this.updateRepositoryInfo(r);
256

    
257
            return repos;
258
        }catch (Exception e){
259
            LOGGER.debug("Exception on getRepositoriesOfUser" , e);
260
            emailUtils.reportException(e);
261
            throw e;
262
        }
263
    }
264

    
265
    @Override
266
    public Repository getRepositoryById(String id) throws JSONException,ResourceNotFoundException {
267

    
268
        LOGGER.debug("Retreiving repositories with id : " + id );
269
        Repository repo = null;
270
        UriComponents uriComponents = searchDatasource("0","100");
271
        RequestFilter requestFilter = new RequestFilter();
272
        requestFilter.setId(id);
273

    
274
        try{
275
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
276
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
277

    
278
            if(jsonArray.length() == 0)
279
                throw new ResourceNotFoundException();
280

    
281
            repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
282
            return updateRepositoryInfo(repo);
283
        }catch (JSONException e){
284
            LOGGER.debug("Exception on getRepositoryById" , e);
285
            emailUtils.reportException(e);
286
            throw e;
287
        }
288

    
289
    }
290

    
291

    
292
    @Override
293
    public List<AggregationDetails> getRepositoryAggregations(String id) throws JSONException {
294

    
295
        LOGGER.debug("Retreiving aggregations for repository with id : " + id );
296
        UriComponents uriComponents = searchDatasource("0","100");
297
        RequestFilter requestFilter = new RequestFilter();
298
        requestFilter.setId(id);
299

    
300
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
301

    
302
        try {
303
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
304
            JSONObject repository = new JSONObject(rs);
305

    
306
            if(repository.getJSONArray("datasourceInfo").length() == 0)
307
                return aggregationHistory;
308
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
309
            return aggregationHistory.size() == 0? aggregationHistory : aggregationHistory.stream()
310
                                                    .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
311
                                                    .limit(20)
312
                                                    .collect(Collectors.toList());
313
        } catch (JSONException e) {
314
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
315
            emailUtils.reportException(e);
316
            throw e;
317
        }
318

    
319
    }
320

    
321
    @Override
322
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(String id) throws JSONException {
323
        LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id );
324
        UriComponents uriComponents = searchDatasource("0","100");
325
        RequestFilter requestFilter = new RequestFilter();
326
        requestFilter.setId(id);
327

    
328
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
329
        Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
330
        try {
331
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
332
            JSONObject repository = new JSONObject(rs);
333

    
334
            if(repository.getJSONArray("datasourceInfo").length() == 0)
335
                return aggregationByYear;
336

    
337
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
338
            return aggregationHistory.size() == 0? aggregationByYear:createYearMap(aggregationHistory);
339

    
340
        } catch (JSONException e) {
341
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
342
            emailUtils.reportException(e);
343
            throw e;
344
        }
345
    }
346

    
347
    private Map<String,List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
348
        Map<String, List<AggregationDetails>> aggregationByYear;
349
        aggregationHistory = aggregationHistory.stream()
350
                            .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
351
                            .collect(Collectors.toList());
352

    
353
       return aggregationHistory.stream()
354
                            .collect(Collectors.groupingBy(AggregationDetails::getYear));
355
    }
356

    
357

    
358
    @Override
359
    public List<Repository> getRepositoriesByName(String name,
360
                                                  String page,
361
                                                  String size) throws JSONException {
362

    
363
        LOGGER.debug("Retreiving  repositories with official name : " + name );
364
        UriComponents uriComponents = searchDatasource("0","100");
365
        RequestFilter requestFilter = new RequestFilter();
366
        requestFilter.setOfficialname(name);
367

    
368
        try{
369
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
370
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
371
            for (Repository r : repos)
372
                updateRepositoryInfo(r);
373
            return repos;
374
        }catch (Exception e){
375
            LOGGER.debug("Exception on getRepositoriesByName" , e);
376
            emailUtils.reportException(e);
377
            throw e;
378
        }
379

    
380
    }
381

    
382
    @Override
383
    public List<RepositoryInterface> getRepositoryInterface(String id) throws JSONException {
384

    
385
        UriComponents uriComponents = UriComponentsBuilder
386
                .fromHttpUrl(baseAddress + "/ds/api/")
387
                .path("/{id}")
388
                .build().expand(id).encode();
389

    
390
        try{
391
            String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
392
            return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
393
        }catch (Exception e ){
394
            LOGGER.debug("Exception on getRepositoryInterface" , e);
395
            emailUtils.reportException(e);
396
            throw e;
397
        }
398

    
399
    }
400

    
401
    @Override
402
    public Repository addRepository(String datatype,
403
                                    Repository repository) throws Exception {
404

    
405
        LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
406

    
407
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
408
        repository.setActivationId(UUID.randomUUID().toString());
409
        repository.setCollectedFrom("infrastruct_::openaire");
410

    
411
        if (datatype.equals("journal")) {
412
            repository.setId("openaire____::issn" + repository.getIssn());
413
            repository.setNamespacePrefix("issn" + repository.getIssn());
414
            this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
415
        }else if (datatype.equals("aggregator")) {
416
            repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
417
            repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0,12));
418
            this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
419
        }else {
420
            this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication());
421
        }
422

    
423
        return repository;
424
    }
425

    
426
    /* update method acting as add -> send email with registration topic/body*/
427
    private Repository latentUpdate(Repository repository, Authentication authentication) throws Exception {
428
        UriComponents uriComponents = UriComponentsBuilder
429
                .fromHttpUrl(baseAddress + "/ds/update/")
430
                .build()
431
                .encode();
432

    
433
        try {
434
            String json_repository = Converter.repositoryObjectToJson(repository);
435
            LOGGER.debug("JSON to add(update) -> " + json_repository);
436

    
437
            HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
438
            ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity, ResponseEntity.class);
439

    
440
            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
441
                emailUtils.sendUserRegistrationEmail(repository, authentication);
442
                emailUtils.sendAdminRegistrationEmail(repository, authentication);
443
            } else
444
                LOGGER.debug(responseEntity.getBody().toString());
445

    
446
            return repository;
447
        } catch (Exception e) {
448
            LOGGER.debug("Exception on updateRepository" , e);
449
            emailUtils.reportException(e);
450
            throw e;
451
        }
452

    
453

    
454
    }
455

    
456
    @Override
457
    public Repository updateRepository(Repository repository,Authentication authentication) throws Exception {
458
        UriComponents uriComponents = UriComponentsBuilder
459
                .fromHttpUrl(baseAddress + "/ds/update/")
460
                .build()
461
                .encode();
462

    
463
        try {
464
            String json_repository = Converter.repositoryObjectToJson(repository);
465

    
466
            LOGGER.debug("JSON to update -> " + json_repository);
467

    
468
            HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
469
            ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity
470
                    , ResponseEntity.class);
471

    
472
            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
473
                emailUtils.sendUserUpdateRepositoryEmail(repository, authentication);
474
                emailUtils.sendAdminUpdateRepositoryEmail(repository, authentication);
475
            } else
476
                LOGGER.debug(responseEntity.getBody().toString());
477

    
478
            return repository;
479
        } catch (Exception e) {
480
            LOGGER.debug("Exception on updateRepository" , e);
481
            emailUtils.reportException(e);
482
            throw e;
483
        }
484
    }
485

    
486
    private void storeRepository(Repository repository, Authentication authentication) throws Exception {
487

    
488
        Date utilDate = new Date();
489
        Timestamp date = new Timestamp(utilDate.getTime());
490
        repository.setDateOfCollection(date);
491
        repository.setAggregator("OPENAIRE");
492
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
493

    
494
        UriComponents uriComponents = UriComponentsBuilder
495
                .fromHttpUrl(baseAddress + "/ds/add/")
496
                .build()
497
                .encode();
498
        String json_repository = Converter.repositoryObjectToJson(repository);
499
        HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
500
        ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity, ResponseEntity.class);
501

    
502
        if(responseEntity.getStatusCode().equals(HttpStatus.OK)) {
503
            emailUtils.sendUserRegistrationEmail(repository, authentication);
504
            emailUtils.sendAdminRegistrationEmail(repository, authentication);
505
        } else {
506
            LOGGER.debug(responseEntity.getBody().toString());
507
        }
508
    }
509

    
510
    @Override
511
    public void deleteRepositoryInterface(String id ,
512
                                          String registeredBy){
513
        UriComponents uriComponents = UriComponentsBuilder
514
                .fromHttpUrl(baseAddress + "/ds/api/")
515
                .path("/{id}")
516
                .build().expand(id).encode();
517
        LOGGER.debug(uriComponents.toUri());
518
        restTemplate.delete(uriComponents.toUri());
519
    }
520

    
521
    @Override
522
    public RepositoryInterface addRepositoryInterface(String datatype,
523
                                                      String repoId,
524
                                                      String registeredBy,
525
                                                      RepositoryInterface repositoryInterface) throws JSONException, ResourceNotFoundException, ValidatorServiceException {
526
        try {
527
            Repository e = this.getRepositoryById(repoId);
528
            repositoryInterface = createRepositoryInterface(e,repositoryInterface,datatype);
529
            String json_interface = Converter.repositoryInterfaceObjectToJson(e,repositoryInterface);
530

    
531
            UriComponents uriComponents = UriComponentsBuilder
532
                    .fromHttpUrl(baseAddress + "/ds/api/add/")
533
                    .build()
534
                    .encode();
535

    
536
            HttpEntity<String> httpEntity = new HttpEntity <> (json_interface,httpHeaders);
537
            restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
538
            submitInterfaceValidation(e, registeredBy, repositoryInterface);
539

    
540
            return repositoryInterface;
541

    
542
        } catch (JSONException | ValidatorServiceException e) {
543
            LOGGER.debug("Exception on addRepositoryInterface" , e);
544
            emailUtils.reportException(e);
545
            throw e;
546
        }
547
    }
548

    
549
    @Override
550
    public RepositoryInterface updateRepositoryInterface(String repoId,
551
                                                         String registeredBy,
552
                                                         RepositoryInterface repositoryInterface) throws Exception {
553

    
554
        this.updateBaseUrl(repoId,repositoryInterface.getId(),repositoryInterface.getBaseUrl());
555
        this.updateCompliance(repoId,repositoryInterface.getId(),repositoryInterface.getCompliance());
556
        this.updateValidationSet(repoId,repositoryInterface.getId(),repositoryInterface.getAccessSet());
557
        submitInterfaceValidation(getRepositoryById(repoId),registeredBy,repositoryInterface);
558
        return repositoryInterface;
559
    }
560

    
561
    private void submitInterfaceValidation(Repository repo, String userEmail, RepositoryInterface iFace) throws ValidatorServiceException {
562
        JobForValidation job = new JobForValidation();
563

    
564
        job.setActivationId(UUID.randomUUID().toString());
565
        job.setAdminEmails(Collections.singletonList(this.adminEmail));
566
        job.setBaseUrl(iFace.getBaseUrl());
567
        job.setDatasourceId(repo.getId());
568
        job.setDesiredCompatibilityLevel(iFace.getDesiredCompatibilityLevel());
569
        job.setInterfaceId(iFace.getId());
570
        job.setOfficialName(repo.getOfficialName());
571
        job.setRepoType(repo.getDatasourceType());
572
        job.setUserEmail(userEmail);
573
        job.setValidationSet((iFace.getAccessSet().isEmpty() ? "none" : iFace.getAccessSet()));
574
        job.setRecords(-1);
575
        job.setRegistration(true);
576
        job.setUpdateExisting(false);
577

    
578
        this.validatorService.submitJobForValidation(job);
579
    }
580

    
581
    private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
582

    
583
        iFace.setContentDescription("metadata");
584
        iFace.setCompliance("UNKNOWN");
585

    
586
        if (datatype.equals("re3data"))
587
            iFace.setAccessFormat("oai_datacite");
588
        else
589
            iFace.setAccessFormat("oai_dc");
590

    
591

    
592
        if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty())
593
            iFace.setTypology(repo.getDatasourceClass());
594
        else if (datatype.equalsIgnoreCase("journal"))
595
            iFace.setTypology("pubsrepository::journal");
596
        else if (datatype.equalsIgnoreCase("aggregator"))
597
            iFace.setTypology("aggregator::pubsrepository::unknown");
598
        else if (datatype.equalsIgnoreCase("opendoar"))
599
            iFace.setTypology("pubsrepository::unknown");
600
        else if (datatype.equalsIgnoreCase("re3data"))
601
            iFace.setTypology("datarepository::unknown");
602

    
603
        iFace.setRemovable(true);
604
        iFace.setAccessProtocol("oai");
605
        iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
606
        iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
607
        if (iFace.getAccessSet() == null || iFace.getAccessSet().isEmpty()) {
608
            LOGGER.debug("set is empty: " + iFace.getAccessSet());
609
            iFace.removeAccessSet();
610
            iFace.setAccessSet("none");
611
        }
612
        return iFace;
613
    }
614

    
615
    @Override
616
    public List<String> getDnetCountries() {
617
        LOGGER.debug("Getting dnet-countries!");
618
        return Converter.readFile("countries.txt");
619
    }
620

    
621
    @Override
622
    public List<String> getTypologies() {
623
        return Converter.readFile("typologies.txt");
624
    }
625

    
626
    @Override
627
    public List<Timezone> getTimezones() {
628
        List<String> timezones =  Converter.readFile("timezones.txt");
629
        return Converter.toTimezones(timezones);
630
    }
631

    
632
    @Override
633
    public List<String> getUrlsOfUserRepos(String userEmail,
634
                                           String page,
635
                                           String size){
636
        UriComponents uriComponents = UriComponentsBuilder
637
                .fromHttpUrl(baseAddress + "/api/baseurl/")
638
                .path("/{page}/{size}")
639
                .build().expand(page,size).encode();
640

    
641
        try{
642
            RequestFilter requestFilter = new RequestFilter();
643
            requestFilter.setRegisteredby(userEmail);
644
            return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(),requestFilter, String[].class));
645
        }catch (Exception e){
646
            LOGGER.debug("Exception on addRepositoryInterface" , e);
647
            emailUtils.reportException(e);
648
            throw e;
649
        }
650
    }
651

    
652
    @Override
653
    public List<String> getDatasourceVocabularies(String mode) {
654

    
655
        List<String> resultSet = new ArrayList<>();
656
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
657
            if (mode.equalsIgnoreCase("aggregator")) {
658
                if (entry.getKey().contains("aggregator"))
659
                    resultSet.add(entry.getValue());
660
            } else if (mode.equalsIgnoreCase("journal")) {
661
                if (entry.getKey().contains("journal"))
662
                    resultSet.add(entry.getValue());
663
            } else if (mode.equalsIgnoreCase("opendoar")) {
664
                if (entry.getKey().contains("pubsrepository"))
665
                    resultSet.add(entry.getValue());
666
            } else if (mode.equalsIgnoreCase("re3data")) {
667
                if (entry.getKey().contains("datarepository"))
668
                    resultSet.add(entry.getValue());
669
            }
670
        }
671

    
672

    
673
        return resultSet;
674
    }
675

    
676
    private Vocabulary getVocabulary(String vocName) {
677

    
678
        if (!vocabularyMap.containsKey(vocName)) {
679
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
680
        }
681
        return vocabularyMap.get(vocName);
682
    }
683

    
684

    
685
    @Override
686
    public Map<String, String> getCompatibilityClasses(String mode)  {
687

    
688
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
689
        Map<String, String> retMap = new HashMap<String, String>();
690

    
691
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
692
        boolean foundData = false;
693
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
694
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
695
                return compatibilityClasses;
696
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
697
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
698
                    retMap.put(entry.getKey(), entry.getValue());
699
                    foundData = true;
700
                }
701
            } else {
702
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
703
                    retMap.put(entry.getKey(), entry.getValue());
704
            }
705
        }
706

    
707
        //TODO TO BE REMOVED WHEN VOCABULARIES ARE UPDATED
708
        if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA) && !foundData)
709
            retMap.put("openaire2.0_data", "OpenAIRE Data (funded, referenced datasets)");
710

    
711
        return retMap;
712
    }
713

    
714
    @Override
715
    public Map<String, String> getDatasourceClasses(String mode)  {
716

    
717
        LOGGER.debug("Getting datasource classes for mode: " + mode);
718

    
719
        Map<String, String> retMap = new HashMap<String, String>();
720

    
721
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
722
            if (mode.equalsIgnoreCase("aggregator")) {
723
                if (entry.getKey().contains("aggregator"))
724
                    retMap.put(entry.getKey(), entry.getValue());
725
            } else if (mode.equalsIgnoreCase("journal")) {
726
                if (entry.getKey().contains("journal"))
727
                    retMap.put(entry.getKey(), entry.getValue());
728
            } else if (mode.equalsIgnoreCase("opendoar")) {
729
                if (entry.getKey().contains("pubsrepository"))
730
                    retMap.put(entry.getKey(), entry.getValue());
731
            } else if (mode.equalsIgnoreCase("re3data")) {
732
                if (entry.getKey().contains("datarepository"))
733
                    retMap.put(entry.getKey(), entry.getValue());
734
            }
735
        }
736
        return filterResults(retMap,mode);
737

    
738
    }
739

    
740
    private Map<String,String> filterResults(Map<String, String> map,String mode) {
741

    
742
        HashMap<String,String> filteredMap = new HashMap<>();
743
        for(String key:map.keySet())
744
            if(dataSourceClass.get(mode).contains(key))
745
                filteredMap.put(key,map.get(key));
746

    
747
        return filteredMap;
748
    }
749

    
750
    @Override
751
    public String getCountryName(String countryCode) {
752
        return inverseCountriesMap.get(countryCode);
753
    }
754

    
755
    @Override
756
    public MetricsInfo getMetricsInfoForRepository(String repoId) throws RepositoryServiceException {
757
        try {
758

    
759
            MetricsInfo metricsInfo = new MetricsInfo();
760
            metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
761
            metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
762
            return metricsInfo;
763

    
764
        } catch (Exception e) {
765
            LOGGER.error("Error while getting metrics info for repository: ", e);
766
            emailUtils.reportException(e);
767
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
768
        }
769
    }
770

    
771
    @Override
772
    public Map<String, String> getListLatestUpdate(String mode) throws JSONException {
773
        if(mode.equals("opendoar"))
774
            return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(0).getLastCollectionDate());
775
        else
776
            /*
777
            * first api of re3data has null value on collection date
778
            * */
779
            return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(1).getLastCollectionDate());
780
    }
781

    
782
    private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) throws Exception {
783
        UriComponents uriComponents = UriComponentsBuilder
784
                .fromHttpUrl(baseAddress + "/ds/api/oaiset")
785
                .queryParam("dsId",repositoryId)
786
                .queryParam("apiId",repositoryInterfaceId)
787
                .queryParam("oaiSet",validationSet)
788
                .build().encode();
789
       restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, null, ResponseEntity.class);
790

    
791
    }
792

    
793

    
794
    private void updateBaseUrl(String repositoryId, String repositoryInterfaceId, String baseUrl) {
795
        UriComponents uriComponents = UriComponentsBuilder
796
                .fromHttpUrl(baseAddress + "/ds/api/baseurl")
797
                .queryParam("dsId",repositoryId)
798
                .queryParam("apiId",repositoryInterfaceId)
799
                .queryParam("baseUrl",baseUrl)
800
                .build().encode();
801
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
802
    }
803

    
804
    private void updateCompliance(String repositoryId, String repositoryInterfaceId,String compliance) {
805
        UriComponents uriComponents = UriComponentsBuilder
806
                .fromHttpUrl(baseAddress + "/ds/api/compliance")
807
                .queryParam("dsId",repositoryId)
808
                .queryParam("apiId",repositoryInterfaceId)
809
                .queryParam("compliance",compliance)
810
                .build().encode();
811
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
812
    }
813

    
814
    private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
815

    
816
        //build the uri params
817
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
818

    
819
        //create new template engine
820
        RestTemplate template = new RestTemplate();
821
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
822
        ResponseEntity<MetricsNumbers> resp;
823
        try {
824
            //communicate with endpoint
825
            resp = template.exchange(
826
                    builder.build().encode().toUri(),
827
                    HttpMethod.GET,
828
                    null,
829
                    new ParameterizedTypeReference<MetricsNumbers>() {
830
                    });
831
        } catch (RestClientException e) {
832
            LOGGER.debug("Exception on getMetricsNumbers" , e);
833
            emailUtils.reportException(e);
834
            throw e;
835
        }
836

    
837
        return resp.getBody();
838
    }
839

    
840
    private String getOpenAIREId(String repoId) {
841

    
842
        if (repoId != null && repoId.contains("::")) {
843
            return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
844
        }
845

    
846
        return null;
847
    }
848

    
849
    private UriComponents searchDatasource(String page,String size){
850

    
851
        return UriComponentsBuilder
852
                .fromHttpUrl(baseAddress + "/ds/search/")
853
                .path("/{page}/{size}/")
854
                .queryParam("requestSortBy","officialname")
855
                .queryParam("order","ASCENDING")
856
                .build().expand(page, size).encode();
857
    }
858

    
859
    private UriComponents searchSnipperDatasource(String page,String size){
860

    
861
        return UriComponentsBuilder
862
                .fromHttpUrl(baseAddress + "/ds/searchsnippet/")
863
                .path("/{page}/{size}/")
864
                .queryParam("requestSortBy","officialname")
865
                .queryParam("order","ASCENDING")
866
                .build().expand(page, size).encode();
867
    }
868

    
869
    private UriComponents searchRegisteredDatasource(String requestSortBy, String order, String page,String size){
870

    
871
        return UriComponentsBuilder
872
                .fromHttpUrl(baseAddress + "/ds/searchregistered/")
873
                .path("/{page}/{size}/")
874
                .queryParam("requestSortBy",requestSortBy)
875
                .queryParam("order",order)
876
                .build().expand(page, size).encode();
877
    }
878

    
879
    private String getRepositoryType(String typology){
880
        return invertedDataSourceClass.get(typology);
881
    }
882

    
883

    
884
}
(12-12/20)