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

    
36
import javax.annotation.PostConstruct;
37
import java.io.IOException;
38
import java.sql.Timestamp;
39
import java.util.*;
40
import java.util.concurrent.ConcurrentHashMap;
41
import java.util.stream.Collectors;
42

    
43
@Service("repositoryService")
44
public class RepositoryServiceImpl implements RepositoryService {
45

    
46
    @Value("${api.baseAddress}")
47
    private String baseAddress;
48

    
49
    private RestTemplate restTemplate = null;
50

    
51
    private HttpHeaders httpHeaders;
52

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

    
55
    private static final Logger LOGGER = Logger.getLogger(RepositoryServiceImpl.class);
56

    
57
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
58
    private String usageStatisticsDiagramsBaseURL;
59

    
60
    @Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
61
    private String usageStatisticsNumbersBaseURL;
62

    
63
    @Autowired
64
    private VocabularyLoader vocabularyLoader;
65

    
66
    @Autowired
67
    private PiWikService piWikService;
68

    
69
    @Autowired
70
    private EmailUtils emailUtils;
71

    
72

    
73
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
74

    
75
    private Map<String, String> countriesMap = new HashMap<>();
76
    private Map<String, String> inverseCountriesMap = new HashMap<>();
77

    
78
    private static Map<String,List<String>> dataSourceClass = new HashMap<String,List<String>>(){{
79
        put("opendoar",new ArrayList<String>(){{ add("pubsrepository::institutional");
80
                                                    add("pubsrepository::thematic");
81
                                                    add("pubsrepository::unknown");
82
                                                    add("pubsrepository::mock");
83
        }});
84
        put("re3data",new ArrayList<String>(){{ add("datarepository::unknown");
85
        }});
86
        put("journal",new ArrayList<String>(){{ add("pubsrepository::journal");
87
        }});
88
        put("aggregator",new ArrayList<String>(){{ add("aggregator::pubsrepository::institutional");
89
                                                        add("aggregator::pubsrepository::journals");
90
                                                        add("aggregator::datarepository");
91
                                                        add("aggregator::pubsrepository::unknown");
92
        }});
93
    }};
94

    
95
    private static Map<String,String> invertedDataSourceClass = new HashMap<String,String>(){{
96
        put("pubsrepository::institutional","opendoar");
97
        put("pubsrepository::thematic","opendoar");
98
        put("pubsrepository::unknown","opendoar");
99
        put("pubsrepository::mock","opendoar");
100

    
101
        put("datarepository::unknown","re3data");
102

    
103
        put("pubsrepository::journal","journal");
104

    
105
        put("aggregator::pubsrepository::institutional","aggregator");
106
        put("aggregator::pubsrepository::journals","aggregator");
107
        put("aggregator::datarepository","aggregator");
108
        put("aggregator::pubsrepository::unknown","aggregator");
109

    
110
    }};
111

    
112

    
113

    
114
    @PostConstruct
115
    private void init() {
116
        LOGGER.debug("Initialization method of repository api!");
117
        LOGGER.debug("Updated version!");
118

    
119
        restTemplate = new RestTemplate();
120
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
121

    
122
        httpHeaders = new HttpHeaders();
123
        httpHeaders.set("Content-Type", "application/json;charset=UTF-8");
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(piWikService.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
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
221
                                                  @PathVariable("page") String page,
222
                                                  @PathVariable("size") String size) throws JSONException {
223

    
224
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
225
        UriComponents uriComponents = searchDatasource(page,size);
226
        RequestFilter requestFilter = new RequestFilter();
227
        requestFilter.setRegisteredby(userEmail);
228

    
229
        try{
230
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
231

    
232
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
233
            for (Repository r : repos)
234
                this.updateRepositoryInfo(r);
235

    
236
            return repos;
237
        }catch (Exception e){
238
            LOGGER.debug("Exception on getRepositoriesOfUser" , e);
239
            emailUtils.reportException(e);
240
            throw e;
241
        }
242
    }
243

    
244
    @Override
245
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException,ResourceNotFoundException {
246

    
247
        LOGGER.debug("Retreiving repositories with id : " + id );
248
        Repository repo = null;
249
        UriComponents uriComponents = searchDatasource("0","100");
250
        RequestFilter requestFilter = new RequestFilter();
251
        requestFilter.setId(id);
252

    
253
        try{
254
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
255
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
256

    
257
            if(jsonArray.length() == 0)
258
                throw new ResourceNotFoundException();
259

    
260
            repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
261
            return updateRepositoryInfo(repo);
262
        }catch (JSONException e){
263
            LOGGER.debug("Exception on getRepositoryById" , e);
264
            emailUtils.reportException(e);
265
            throw e;
266
        }
267

    
268
    }
269

    
270

    
271
    @Override
272
    public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
273

    
274
        LOGGER.debug("Retreiving aggregations for repository with id : " + id );
275
        UriComponents uriComponents = searchDatasource("0","100");
276
        RequestFilter requestFilter = new RequestFilter();
277
        requestFilter.setId(id);
278

    
279
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
280

    
281
        try {
282
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
283
            JSONObject repository = new JSONObject(rs);
284

    
285
            if(repository.getJSONArray("datasourceInfo").length() == 0)
286
                return aggregationHistory;
287
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
288
            return aggregationHistory.size() == 0? aggregationHistory : aggregationHistory.stream()
289
                                                    .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
290
                                                    .limit(20)
291
                                                    .collect(Collectors.toList());
292
        } catch (JSONException e) {
293
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
294
            emailUtils.reportException(e);
295
            throw e;
296
        }
297

    
298
    }
299

    
300
    @Override
301
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
302
        LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id );
303
        UriComponents uriComponents = searchDatasource("0","100");
304
        RequestFilter requestFilter = new RequestFilter();
305
        requestFilter.setId(id);
306

    
307
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
308
        Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
309
        try {
310
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
311
            JSONObject repository = new JSONObject(rs);
312

    
313
            if(repository.getJSONArray("datasourceInfo").length() == 0)
314
                return aggregationByYear;
315

    
316
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
317
            return aggregationHistory.size() == 0? aggregationByYear:createYearMap(aggregationHistory);
318

    
319
        } catch (JSONException e) {
320
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
321
            emailUtils.reportException(e);
322
            throw e;
323
        }
324
    }
325

    
326
    private Map<String,List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
327
        Map<String, List<AggregationDetails>> aggregationByYear;
328
        aggregationHistory = aggregationHistory.stream()
329
                            .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
330
                            .collect(Collectors.toList());
331

    
332
       return aggregationHistory.stream()
333
                            .collect(Collectors.groupingBy(AggregationDetails::getYear));
334
    }
335

    
336

    
337
    @Override
338
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
339
                                                  @PathVariable("page") String page,
340
                                                  @PathVariable("size") String size) throws JSONException {
341

    
342
        LOGGER.debug("Retreiving  repositories with official name : " + name );
343
        UriComponents uriComponents = searchDatasource("0","100");
344
        RequestFilter requestFilter = new RequestFilter();
345
        requestFilter.setOfficialname(name);
346

    
347
        try{
348
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
349
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
350
            for (Repository r : repos)
351
                updateRepositoryInfo(r);
352
            return repos;
353
        }catch (Exception e){
354
            LOGGER.debug("Exception on getRepositoriesByName" , e);
355
            emailUtils.reportException(e);
356
            throw e;
357
        }
358

    
359
    }
360

    
361
    @Override
362
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
363

    
364
        UriComponents uriComponents = UriComponentsBuilder
365
                .fromHttpUrl(baseAddress + "/ds/api/")
366
                .path("/{id}")
367
                .build().expand(id).encode();
368

    
369
        try{
370
            String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
371
            return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
372
        }catch (Exception e ){
373
            LOGGER.debug("Exception on getRepositoryInterface" , e);
374
            emailUtils.reportException(e);
375
            throw e;
376
        }
377

    
378
    }
379

    
380
    @Override
381
    public Repository addRepository(@RequestParam("datatype") String datatype,
382
                                    @RequestBody Repository repository) throws Exception {
383

    
384
        LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
385

    
386
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
387
        repository.setActivationId(UUID.randomUUID().toString());
388
        repository.setCollectedFrom("infrastruct_::openaire");
389

    
390
        if (datatype.equals("journal")) {
391
            repository.setId("openaire____::issn" + repository.getIssn());
392
            repository.setNamespacePrefix("issn" + repository.getIssn());
393
            this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
394
        }else if (datatype.equals("aggregator")) {
395
            repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
396
            repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0,12));
397
            this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
398
        }else {
399
            this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication());
400
        }
401

    
402
        return repository;
403
    }
404

    
405
    /* update method acting as add -> send email with registration topic/body*/
406
    private Repository latentUpdate(Repository repository, Authentication authentication) throws Exception {
407
        UriComponents uriComponents = UriComponentsBuilder
408
                .fromHttpUrl(baseAddress + "/ds/update/")
409
                .build()
410
                .encode();
411

    
412
        try {
413
            String json_repository = Converter.repositoryObjectToJson(repository);
414
            LOGGER.debug("JSON to add(update) -> " + json_repository);
415

    
416
            HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
417
            ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity, ResponseEntity.class);
418

    
419
            if (responseEntity.getStatusCode().equals(HttpStatus.OK))
420
                emailUtils.sendUserRegistrationEmail(repository, authentication);
421
            else
422
                LOGGER.debug(responseEntity.getBody().toString());
423

    
424
            return repository;
425
        } catch (Exception e) {
426
            LOGGER.debug("Exception on updateRepository" , e);
427
            emailUtils.reportException(e);
428
            throw e;
429
        }
430

    
431

    
432
    }
433

    
434
    @Override
435
    public Repository updateRepository(@RequestBody Repository repository,Authentication authentication) throws Exception {
436
        UriComponents uriComponents = UriComponentsBuilder
437
                .fromHttpUrl(baseAddress + "/ds/update/")
438
                .build()
439
                .encode();
440

    
441
        try {
442
            String json_repository = Converter.repositoryObjectToJson(repository);
443

    
444
            LOGGER.debug("JSON to update -> " + json_repository);
445

    
446
            HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
447
            ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity, ResponseEntity.class);
448

    
449
            if (responseEntity.getStatusCode().equals(HttpStatus.OK))
450
                emailUtils.sendUserUpdateRepositoryEmail(repository, authentication);
451
            else
452
                LOGGER.debug(responseEntity.getBody().toString());
453

    
454
            return repository;
455
        } catch (Exception e) {
456
            LOGGER.debug("Exception on updateRepository" , e);
457
            emailUtils.reportException(e);
458
            throw e;
459
        }
460
    }
461

    
462
    private void updateInterface(String datatype,RepositoryInterface iFace) {
463
        //TODO call update base url
464
        //((DatasourceManagerService) this.dmService.getService()).updateBaseUrl(repo.getId(), iFace.getId(), iFace.getBaseUrl());
465
        if (!iFace.getAccessSet().isEmpty()) {
466
            LOGGER.debug("set not empty: " + iFace.getAccessSet());
467
            //TODO call update method for access params
468
            // ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "set", iFace.getAccessSet(), false);
469
        } else {
470
            //TODO call deleteAccessParamOrExtraField
471
            //((DatasourceManagerService) this.dmService.getService()).deleteAccessParamOrExtraField(repo.getId(), iFace.getId(), "set");
472
        }
473
        //TODO update content description
474
        //((DatasourceManagerService) this.dmService.getService()).updateContentDescription(repo.getId(), iFace.getId(), "metadata");
475
        if (datatype.equals("re3data")) {
476
            //TODO call update access params
477
            //  ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_datacite", false);
478
            iFace.setAccessFormat("oai_datacite");
479
        } else {
480
            //TODO call update access params
481
            //((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_dc", false);
482
            iFace.setAccessFormat("oai_dc");
483
        }
484

    
485
    }
486

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

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

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

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

    
510
    @Override
511
    public void deleteRepositoryInterface(@RequestParam("id") String id ,
512
                                          @RequestParam("registeredBy") 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(@RequestParam("datatype") String datatype,
523
                                                      @RequestParam("repoId") String repoId,
524
                                                      @RequestParam("registeredBy") String registeredBy,
525
                                                      @RequestBody RepositoryInterface repositoryInterface) throws JSONException,ResourceNotFoundException {
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 <String> (json_interface,httpHeaders);
537
            restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
538
            return repositoryInterface;
539

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

    
547
    private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
548

    
549
        iFace.setContentDescription("metadata");
550
        iFace.setCompliance("UNKNOWN");
551

    
552
        if (datatype.equals("re3data"))
553
            iFace.setAccessFormat("oai_datacite");
554
        else
555
            iFace.setAccessFormat("oai_dc");
556

    
557

    
558
        if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty())
559
            iFace.setTypology(repo.getDatasourceClass());
560
        else if (datatype.equalsIgnoreCase("journal"))
561
            iFace.setTypology("pubsrepository::journal");
562
        else if (datatype.equalsIgnoreCase("aggregator"))
563
            iFace.setTypology("aggregator::pubsrepository::unknown");
564
        else if (datatype.equalsIgnoreCase("opendoar"))
565
            iFace.setTypology("pubsrepository::unknown");
566
        else if (datatype.equalsIgnoreCase("re3data"))
567
            iFace.setTypology("datarepository::unknown");
568

    
569
        iFace.setRemovable(true);
570
        iFace.setAccessProtocol("oai");
571
        iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
572
        iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
573
        if (iFace.getAccessSet().isEmpty()) {
574
            LOGGER.debug("set is empty: " + iFace.getAccessSet());
575
            iFace.removeAccessSet();
576
        }
577
        return iFace;
578
    }
579

    
580
    @Override
581
    public List<String> getDnetCountries() {
582
        LOGGER.debug("Getting dnet-countries!");
583
        return Converter.readFile("countries.txt");
584
    }
585

    
586
    @Override
587
    public List<String> getTypologies() {
588
        return Converter.readFile("typologies.txt");
589
    }
590

    
591
    @Override
592
    public List<Timezone> getTimezones() {
593
        List<String> timezones =  Converter.readFile("timezones.txt");
594
        return Converter.toTimezones(timezones);
595
    }
596

    
597
    @Override
598
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String userEmail,
599
                                           @PathVariable("page") String page,
600
                                           @PathVariable("size") String size) throws JSONException {
601
        UriComponents uriComponents = UriComponentsBuilder
602
                .fromHttpUrl(baseAddress + "/api/baseurl/")
603
                .path("/{page}/{size}")
604
                .build().expand(page,size).encode();
605

    
606
        try{
607
            RequestFilter requestFilter = new RequestFilter();
608
            requestFilter.setRegisteredby(userEmail);
609
            return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(),requestFilter, String[].class));
610
        }catch (Exception e){
611
            LOGGER.debug("Exception on addRepositoryInterface" , e);
612
            emailUtils.reportException(e);
613
            throw e;
614
        }
615
    }
616

    
617
    @Override
618
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
619

    
620
        List<String> resultSet = new ArrayList<>();
621
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
622
            if (mode.equalsIgnoreCase("aggregator")) {
623
                if (entry.getKey().contains("aggregator"))
624
                    resultSet.add(entry.getValue());
625
            } else if (mode.equalsIgnoreCase("journal")) {
626
                if (entry.getKey().contains("journal"))
627
                    resultSet.add(entry.getValue());
628
            } else if (mode.equalsIgnoreCase("opendoar")) {
629
                if (entry.getKey().contains("pubsrepository"))
630
                    resultSet.add(entry.getValue());
631
            } else if (mode.equalsIgnoreCase("re3data")) {
632
                if (entry.getKey().contains("datarepository"))
633
                    resultSet.add(entry.getValue());
634
            }
635
        }
636

    
637

    
638
        return resultSet;
639
    }
640

    
641
    private Vocabulary getVocabulary(String vocName) {
642

    
643
        if (!vocabularyMap.containsKey(vocName)) {
644
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
645
        }
646
        return vocabularyMap.get(vocName);
647
    }
648

    
649

    
650
    @Override
651
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
652

    
653
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
654
        Map<String, String> retMap = new HashMap<String, String>();
655

    
656
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
657
        boolean foundData = false;
658
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
659
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
660
                return compatibilityClasses;
661
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
662
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
663
                    retMap.put(entry.getKey(), entry.getValue());
664
                    foundData = true;
665
                }
666
            } else {
667
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
668
                    retMap.put(entry.getKey(), entry.getValue());
669
            }
670
        }
671

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

    
676
        return retMap;
677
    }
678

    
679
    @Override
680
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
681

    
682
        LOGGER.debug("Getting datasource classes for mode: " + mode);
683

    
684
        Map<String, String> retMap = new HashMap<String, String>();
685

    
686
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
687
            if (mode.equalsIgnoreCase("aggregator")) {
688
                if (entry.getKey().contains("aggregator"))
689
                    retMap.put(entry.getKey(), entry.getValue());
690
            } else if (mode.equalsIgnoreCase("journal")) {
691
                if (entry.getKey().contains("journal"))
692
                    retMap.put(entry.getKey(), entry.getValue());
693
            } else if (mode.equalsIgnoreCase("opendoar")) {
694
                if (entry.getKey().contains("pubsrepository"))
695
                    retMap.put(entry.getKey(), entry.getValue());
696
            } else if (mode.equalsIgnoreCase("re3data")) {
697
                if (entry.getKey().contains("datarepository"))
698
                    retMap.put(entry.getKey(), entry.getValue());
699
            }
700
        }
701
        return filterResults(retMap,mode);
702

    
703
    }
704

    
705
    private Map<String,String> filterResults(Map<String, String> map,String mode) {
706

    
707
        HashMap<String,String> filteredMap = new HashMap<>();
708
        for(String key:map.keySet())
709
            if(dataSourceClass.get(mode).contains(key))
710
                filteredMap.put(key,map.get(key));
711

    
712
        return filteredMap;
713
    }
714

    
715
    @Override
716
    public String getCountryName(String countryCode) {
717
        return inverseCountriesMap.get(countryCode);
718
    }
719

    
720
    @Override
721
    public MetricsInfo getMetricsInfoForRepository(@PathVariable("repoId")  String repoId) throws RepositoryServiceException {
722
        try {
723

    
724
            MetricsInfo metricsInfo = new MetricsInfo();
725
            metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
726
            metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
727
            return metricsInfo;
728

    
729
        } catch (Exception e) {
730
            LOGGER.error("Error while getting metrics info for repository: ", e);
731
            emailUtils.reportException(e);
732
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
733
        }
734
    }
735

    
736
    @Override
737
    public Map<String, String> getListLatestUpdate(@PathVariable("mode")  String mode) throws JSONException {
738
        if(mode.equals("opendoar"))
739
            return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(0).getLastCollectionDate());
740
        else
741
            /*
742
            * first api of re3data has null value on collection date
743
            * */
744
            return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(1).getLastCollectionDate());
745
    }
746

    
747
    @Override
748
    public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String repoId,
749
                                                         @RequestParam("registeredBy") String registeredBy,
750
                                                         @RequestBody RepositoryInterface repositoryInterface) throws Exception {
751

    
752
        this.updateBaseUrl(repoId,repositoryInterface.getId(),repositoryInterface.getBaseUrl());
753
        this.updateCompliance(repoId,repositoryInterface.getId(),repositoryInterface.getCompliance());
754
        this.updateValidationSet(repoId,repositoryInterface.getId(),repositoryInterface.getAccessSet());
755
        return repositoryInterface;
756
    }
757

    
758
    private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) throws Exception {
759
        UriComponents uriComponents = UriComponentsBuilder
760
                .fromHttpUrl(baseAddress + "/ds/api/oaiset")
761
                .queryParam("dsId",repositoryId)
762
                .queryParam("apiId",repositoryInterfaceId)
763
                .queryParam("oaiSet",validationSet)
764
                .build().encode();
765
       restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, null, ResponseEntity.class);
766

    
767
    }
768

    
769

    
770
    private void updateBaseUrl(String repositoryId, String repositoryInterfaceId, String baseUrl) {
771
        UriComponents uriComponents = UriComponentsBuilder
772
                .fromHttpUrl(baseAddress + "/ds/api/baseurl")
773
                .queryParam("dsId",repositoryId)
774
                .queryParam("apiId",repositoryInterfaceId)
775
                .queryParam("baseUrl",baseUrl)
776
                .build().encode();
777
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
778
    }
779

    
780
    private void updateCompliance(String repositoryId, String repositoryInterfaceId,String compliance) {
781
        UriComponents uriComponents = UriComponentsBuilder
782
                .fromHttpUrl(baseAddress + "/ds/api/compliance")
783
                .queryParam("dsId",repositoryId)
784
                .queryParam("apiId",repositoryInterfaceId)
785
                .queryParam("compliance",compliance)
786
                .build().encode();
787
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
788
    }
789

    
790
    private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
791

    
792
        //build the uri params
793
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
794

    
795
        //create new template engine
796
        RestTemplate template = new RestTemplate();
797
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
798
        ResponseEntity<MetricsNumbers> resp;
799
        try {
800
            //communicate with endpoint
801
            resp = template.exchange(
802
                    builder.build().encode().toUri(),
803
                    HttpMethod.GET,
804
                    null,
805
                    new ParameterizedTypeReference<MetricsNumbers>() {
806
                    });
807
        } catch (RestClientException e) {
808
            LOGGER.debug("Exception on getMetricsNumbers" , e);
809
            emailUtils.reportException(e);
810
            throw e;
811
        }
812

    
813
        return resp.getBody();
814
    }
815

    
816
    private String getOpenAIREId(String repoId) {
817

    
818
        if (repoId != null && repoId.contains("::")) {
819
            return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
820
        }
821

    
822
        return null;
823
    }
824

    
825
    private UriComponents searchDatasource(String page,String size){
826

    
827
        return UriComponentsBuilder
828
                .fromHttpUrl(baseAddress + "/ds/search/")
829
                .path("/{page}/{size}/")
830
                .queryParam("requestSortBy","officialname")
831
                .queryParam("order","ASCENDING")
832
                .build().expand(page, size).encode();
833
    }
834

    
835
    private UriComponents searchSnipperDatasource(String page,String size){
836

    
837
        return UriComponentsBuilder
838
                .fromHttpUrl(baseAddress + "/ds/searchsnippet/")
839
                .path("/{page}/{size}/")
840
                .queryParam("requestSortBy","officialname")
841
                .queryParam("order","ASCENDING")
842
                .build().expand(page, size).encode();
843
    }
844

    
845
    private String getRepositoryType(String typology){
846
        return invertedDataSourceClass.get(typology);
847
    }
848

    
849

    
850
}
(10-10/18)