Project

General

Profile

1
package eu.dnetlib.repo.manager.service.controllers;
2

    
3
import com.fasterxml.jackson.databind.DeserializationFeature;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import eu.dnetlib.domain.data.Repository;
6
import eu.dnetlib.domain.data.RepositoryInterface;
7
import eu.dnetlib.domain.enabling.Vocabulary;
8
import eu.dnetlib.repo.manager.service.utils.Converter;
9
import eu.dnetlib.repo.manager.shared.Aggregations;
10
import eu.dnetlib.repo.manager.shared.Constants;
11
import eu.dnetlib.repo.manager.shared.Country;
12
import eu.dnetlib.repo.manager.shared.Timezone;
13
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
14
import org.apache.log4j.Logger;
15
import org.json.JSONArray;
16
import org.json.JSONException;
17
import org.json.JSONObject;
18
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.beans.factory.annotation.Value;
20
import org.springframework.http.HttpEntity;
21
import org.springframework.http.HttpHeaders;
22
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
23
import org.springframework.stereotype.Component;
24
import org.springframework.web.bind.annotation.PathVariable;
25
import org.springframework.web.bind.annotation.RequestBody;
26
import org.springframework.web.bind.annotation.RequestParam;
27
import org.springframework.web.client.RestTemplate;
28
import org.springframework.web.util.UriComponents;
29
import org.springframework.web.util.UriComponentsBuilder;
30

    
31
import javax.annotation.PostConstruct;
32
import java.io.IOException;
33
import java.sql.Timestamp;
34
import java.text.Normalizer;
35
import java.util.*;
36
import java.util.concurrent.ConcurrentHashMap;
37

    
38
@Component
39
public class RepositoryApiImpl implements RepositoryApi {
40

    
41
    @Value("${api.baseAddress}")
42
    private String baseAddress;
43

    
44
    private RestTemplate restTemplate = null;
45

    
46
    private HttpHeaders httpHeaders;
47

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

    
50
    private static final Logger LOGGER = Logger.getLogger(RepositoryApiImpl.class);
51

    
52
    @Autowired
53
    private VocabularyLoader vocabularyLoader;
54

    
55
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
56

    
57
    private Map<String, String> countriesMap = new HashMap<>();
58
    private Map<String, String> inverseCountriesMap = new HashMap<>();
59

    
60

    
61
    @PostConstruct
62
    private void init() {
63
        LOGGER.debug("Initialization method of repository api!");
64

    
65
        restTemplate = new RestTemplate();
66
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
67

    
68
        httpHeaders = new HttpHeaders();
69
        httpHeaders.set("Content-Type", "application/json");
70

    
71
        for (String vocName : vocabularyNames) {
72
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
73
        }
74

    
75
        Country[] countries = getCountries();
76
        for (Country c : countries) {
77
            countriesMap.put(c.getName(), c.getCode());
78
            inverseCountriesMap.put(c.getCode(), c.getName());
79
        }
80

    
81

    
82
    }
83

    
84
    @Override
85
    public List<String> testAggregations() throws JSONException {
86

    
87
        int page = 0;
88
        int size = 1000;
89

    
90
        UriComponents uriComponents = UriComponentsBuilder
91
                .fromHttpUrl(baseAddress + "/ds/list/")
92
                .path("/{page}/{size}/")
93
                .build().expand(page, size).encode();
94

    
95
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
96
        List<String> ids = new ArrayList<>();
97
        while (!rs.equals("[]")) {
98

    
99
            ids.addAll(getIdsWithNonEmptyAggregations(rs));
100

    
101
            LOGGER.debug("Checked " + (page + 1) * size + " records!");
102

    
103
            page += 1;
104
            uriComponents = UriComponentsBuilder
105
                    .fromHttpUrl(baseAddress + "/ds/list/")
106
                    .path("/{page}/{size}/")
107
                    .build().expand(page, size).encode();
108
            rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
109
        }
110

    
111
        return ids;
112
    }
113

    
114
    private List<String> getIdsWithNonEmptyAggregations(String rs) throws JSONException {
115

    
116
        JSONArray ids = new JSONArray(rs);
117
        List<String> agg_ids = new ArrayList<>();
118
        for (int i = 0; i < ids.length(); i++) {
119
            String id = ids.getString(i);
120
            Aggregations aggregations = getRepositoryAggregations(id);
121
            if (aggregations.getAggregationHistory() != null)
122
                agg_ids.add(id);
123
        }
124
        return agg_ids;
125
    }
126

    
127
    @Override
128
    public Country[] getCountries() {
129
        UriComponents uriComponents = UriComponentsBuilder
130
                .fromHttpUrl(baseAddress + "/ds/countries")
131
                .build().encode();
132
        return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
133
    }
134

    
135

    
136
    @Override
137
    public List<Repository> getRepositoriesByCountry(@PathVariable("country") String country,
138
                                                     @PathVariable("mode") String mode) throws JSONException {
139

    
140
        LOGGER.debug("Getting repositories by country!");
141
        int page = 0;
142
        int size = 100;
143

    
144
        String countryCode = countriesMap.get(country);
145
        String filterKey = "UNKNOWN";
146
        if (mode.equalsIgnoreCase("opendoar")) {
147
            filterKey = "openaire____::opendoar";
148
        } else if (mode.equalsIgnoreCase("re3data")) {
149
            filterKey = "openaire____::re3data";
150
        } else if (mode.equalsIgnoreCase("jour_aggr")) {
151
            filterKey = "infrastruct_::openaire";
152
        }
153

    
154
        LOGGER.debug("Country code equals : " + countryCode);
155
        LOGGER.debug("Filter mode equals : " + filterKey);
156
        UriComponents uriComponents = UriComponentsBuilder
157
                .fromHttpUrl(baseAddress + "/ds/search/country/")
158
                .path("/{page}/{size}/")
159
                .queryParam("country", countryCode)
160
                .build().expand(page, size).encode();
161

    
162
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
163
        List<Repository> resultSet = new ArrayList<>();
164
        while (!rs.equals("[]")) {
165
            List<Repository> rep = Converter.jsonToRepositoryList(new JSONArray(rs));
166

    
167
            Collection<Repository> repos = this.getRepositoriesByMode(filterKey, rep);
168
            resultSet.addAll(repos);
169

    
170
            page += 1;
171
            uriComponents = UriComponentsBuilder
172
                    .fromHttpUrl(baseAddress + "/ds/search/country/")
173
                    .path("/{page}/{size}/")
174
                    .queryParam("country", countryCode)
175
                    .build().expand(page, size).encode();
176
            rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
177
        }
178
        for (Repository r : resultSet)
179
            r.setCountryName(getCountryName(r.getCountryCode()));
180
        return resultSet;
181
    }
182

    
183

    
184
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
185

    
186
        List<Repository> reps = new ArrayList<>();
187
        for (Repository r : rs) {
188
            if (r.getCollectedFrom().equals(mode))
189
                reps.add(r);
190
        }
191
        return reps;
192
    }
193

    
194
    @Override
195
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
196
                                                  @PathVariable("page") String page,
197
                                                  @PathVariable("size") String size) throws JSONException {
198

    
199
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
200
        UriComponents uriComponents = UriComponentsBuilder
201
                .fromHttpUrl(baseAddress + "/ds/search/registeredby/")
202
                .path("/{page}/{size}/")
203
                .queryParam("registeredBy", userEmail)
204
                .build().expand(page, size).encode();
205

    
206
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
207
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
208
        for (Repository r : repos){
209
            r.setInterfaces(this.getRepositoryInterface(r.getId()));
210
            r.setCountryName(getCountryName(r.getCountryCode()));
211
        }
212

    
213
        return repos;
214
    }
215

    
216
    @Override
217
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException {
218

    
219
        UriComponents uriComponents = UriComponentsBuilder
220
                .fromHttpUrl(baseAddress + "/ds/get/")
221
                .path("/{id}/")
222
                .build().expand(id).encode();
223

    
224
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
225
        Repository repo = Converter.jsonToRepositoryObject(new JSONObject(rs));
226
        if (repo != null) {
227
            repo.setCountryName(getCountryName(repo.getCountryCode()));
228
            repo.setInterfaces(this.getRepositoryInterface(repo.getId()));
229
        }
230
        return repo;
231
    }
232

    
233

    
234
    @Override
235
    public Aggregations getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
236

    
237
        UriComponents uriComponents = UriComponentsBuilder
238
                .fromHttpUrl(baseAddress + "/ds/get/")
239
                .path("/{id}/")
240
                .build().expand(id).encode();
241

    
242
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
243
        JSONObject repository = new JSONObject(rs);
244

    
245
        Aggregations aggregations = new Aggregations();
246

    
247
        try {
248
            aggregations.setAggregationHistory(Converter.getAggregationHistoryFromJson(repository));
249
            aggregations.setLastCollection(Converter.getLastCollectionFromJson(repository));
250
            aggregations.setLastTransformation(Converter.getLastTransformationFromJson(repository));
251
            return aggregations;
252
        } catch (JSONException e) {
253
            LOGGER.debug("JSON aggregation exception ", e);
254
            throw e;
255
        }
256

    
257
    }
258

    
259
    @Override
260
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
261
                                                  @PathVariable("page") String page,
262
                                                  @PathVariable("size") String size) throws JSONException {
263
        UriComponents uriComponents = UriComponentsBuilder
264
                .fromHttpUrl(baseAddress + "/ds/search/name/")
265
                .path("/{page}/{size}")
266
                .queryParam("name", name)
267
                .build().expand(page, size).encode();
268

    
269
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
270
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
271
        for (Repository r : repos){
272
           // r.setInterfaces(this.getRepositoryInterface(r.getId()));
273
            r.setCountryName(getCountryName(r.getCountryCode()));
274
        }
275
        return repos;
276
    }
277

    
278
    @Override
279
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
280

    
281
        UriComponents uriComponents = UriComponentsBuilder
282
                .fromHttpUrl(baseAddress + "/ds/api/")
283
                .path("/{id}/")
284
                .build().expand(id).encode();
285

    
286
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
287
        return Converter.jsonToRepositoryInterfaceList(new JSONArray(rs));
288
    }
289

    
290
    @Override
291
    public void addRepository(@RequestBody String params) throws Exception {
292

    
293
        JSONObject json_params = new JSONObject(params);
294
        String datatype = json_params.getString("datatype");
295
        String json_repository = json_params.getString("repository");
296
        Repository repository = null;
297
        ObjectMapper mapper = new ObjectMapper();
298
        mapper.disable(DeserializationFeature.FAIL_ON_UNK‌​NOWN_PROPERTIES);
299
        try {
300
            LOGGER.debug("repository -> " + json_repository);
301
            repository = mapper.readValue(json_repository, Repository.class);
302
        } catch (Exception e) {
303
            LOGGER.debug("Error parsing repository ", e);
304
            throw  e;
305
        }
306

    
307
        repository = this.setRepositoryFeatures(datatype,repository);
308

    
309
        LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
310
        if (!datatype.equalsIgnoreCase("opendoar") && !datatype.equalsIgnoreCase("re3data")) {
311
            if (datatype.equalsIgnoreCase("journal") || datatype.equalsIgnoreCase("aggregator")) {
312
                LOGGER.debug("looking if " + datatype + " " + repository.getOfficialName() + " is already in datasources");
313
                if (getRepositoryById(repository.getId()) != null) {
314
                    String retMessage = datatype + " '" + repository.getOfficialName() + "' is already in datasources.";
315
                    repository.getInterfaces().clear();
316
                    LOGGER.debug(retMessage);
317
                } else {
318
                    LOGGER.debug(datatype + " " + repository.getOfficialName() + " is not in datasources. Inserting..");
319
                    this.storeRepository(repository);
320
                }
321
            }
322
        } else {
323
            this.updateRegisteredByValue(repository.getId(),repository.getRegisteredBy());
324
        }
325

    
326
        LOGGER.debug("Inserting Interfaces");
327
        Iterator var11 = repository.getInterfaces().iterator();
328

    
329
        while (var11.hasNext()) {
330
            RepositoryInterface iFace = (RepositoryInterface) var11.next();
331
            if (!iFace.getBaseUrl().isEmpty() && !iFace.getDesiredCompatibilityLevel().isEmpty()) {
332
                if (iFace.getId() != null && !iFace.getId().isEmpty()) {
333
                    LOGGER.debug("updating iface..");
334
                    this.updateInterface(datatype,iFace);
335
                    LOGGER.debug("updated successfully");
336
                } else {
337
                    LOGGER.debug("adding new iface..");
338
                    this.registerRepositoryInterface(repository.getId(),iFace,datatype);
339
                }
340
            }
341
        }
342
    }
343

    
344
    private void updateRegisteredByValue(String id, String registeredBy) {
345

    
346
        LOGGER.debug("Updating registered by value with  : " + registeredBy );
347
        UriComponents uriComponents = UriComponentsBuilder
348
                .fromHttpUrl(baseAddress + "/ds/registeredby/")
349
                .queryParam("dsId",id)
350
                .queryParam("registeredBy", registeredBy)
351
                .build()
352
                .encode();
353

    
354
        restTemplate.postForObject(uriComponents.toUri(), null,String.class);
355
    }
356

    
357
    private Repository setRepositoryFeatures(String datatype, Repository repository) {
358

    
359
        //TODO update map
360
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
361

    
362
        repository.setActivationId(UUID.randomUUID().toString());
363
        // repo.setRegisteredBy((String) session.get(LocalVocabularies.loggedInField));
364

    
365
        if (datatype.equals("opendoar") || datatype.equals("re3data")) {
366
            repository.setProvenanceActionClass("sysimport:crosswalk:entityregistry");
367
        } else if (datatype.equals("journal")) {
368
            repository.setProvenanceActionClass("user:insert");
369
            repository.setCollectedFrom("infrastruct_::openaire");
370
            if (repository.getIssn() != null && repository.getIssn().length() == 0)
371
                repository.setIssn(com.unboundid.util.Base64.encode(repository.getOfficialName()).substring(0, 8));
372
            repository.setId("openaire____::issn" + repository.getIssn());
373
            repository.setNamespacePrefix("issn" + repository.getIssn());
374
        } else if (datatype.equals("aggregator")) {
375
            repository.setProvenanceActionClass("user:insert");
376
            repository.setCollectedFrom("infrastruct_::openaire");
377
            repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
378
            repository.setNamespacePrefix(Normalizer.normalize(repository.getOfficialName().toLowerCase().replace(" ", "_"), Normalizer.Form.NFD).replaceAll("[^a-zA-Z0-9]", ""));
379
            if (repository.getNamespacePrefix().length() > 12) {
380
                repository.setNamespacePrefix(repository.getNamespacePrefix().substring(0, 12));
381
            } else {
382
                while (repository.getNamespacePrefix().length() < 12)
383
                    repository.setNamespacePrefix(repository.getNamespacePrefix().concat("_"));
384
            }
385
        }
386
        return repository;
387
    }
388

    
389
    private void updateInterface(String datatype,RepositoryInterface iFace) {
390
        //TODO call update base url
391
        //((DatasourceManagerService) this.dmService.getService()).updateBaseUrl(repo.getId(), iFace.getId(), iFace.getBaseUrl());
392
        if (!iFace.getAccessSet().isEmpty()) {
393
            LOGGER.debug("set not empty: " + iFace.getAccessSet());
394
            //TODO call update method for access params
395
            // ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "set", iFace.getAccessSet(), false);
396
        } else {
397
            //TODO call deleteAccessParamOrExtraField
398
            //((DatasourceManagerService) this.dmService.getService()).deleteAccessParamOrExtraField(repo.getId(), iFace.getId(), "set");
399
        }
400
        //TODO update content description
401
        //((DatasourceManagerService) this.dmService.getService()).updateContentDescription(repo.getId(), iFace.getId(), "metadata");
402
        if (datatype.equals("re3data")) {
403
            //TODO call update access params
404
            //  ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_datacite", false);
405
            iFace.setAccessFormat("oai_datacite");
406
        } else {
407
            //TODO call update access params
408
            //((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_dc", false);
409
            iFace.setAccessFormat("oai_dc");
410
        }
411

    
412
    }
413

    
414
    private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
415

    
416
        iFace.setContentDescription("metadata");
417
        iFace.setCompliance("UNKNOWN");
418
        if (datatype.equals("re3data")) {
419
            iFace.setAccessFormat("oai_datacite");
420
        } else {
421
            iFace.setAccessFormat("oai_dc");
422
        }
423

    
424
        if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty()) {
425
            iFace.setTypology(repo.getDatasourceClass());
426
        } else if (datatype.equalsIgnoreCase("journal")) {
427
            iFace.setTypology("pubsrepository::journal");
428
        } else if (datatype.equalsIgnoreCase("aggregator")) {
429
            iFace.setTypology("aggregator::pubsrepository::unknown");
430
        } else if (datatype.equalsIgnoreCase("opendoar")) {
431
            iFace.setTypology("pubsrepository::unknown");
432
        } else if (datatype.equalsIgnoreCase("re3data")) {
433
            iFace.setTypology("datarepository::unknown");
434
        }
435

    
436
        iFace.setRemovable(true);
437
        iFace.setAccessProtocol("oai");
438
        iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
439
       // iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
440
        if (iFace.getAccessSet().isEmpty()) {
441
            LOGGER.debug("set is empty: " + iFace.getAccessSet());
442
            iFace.removeAccessSet();
443
        }
444
        return iFace;
445
    }
446

    
447
    private void storeRepository(Repository repository) throws JSONException {
448

    
449
        Date utilDate = new Date();
450
        Timestamp date = new Timestamp(utilDate.getTime());
451
        repository.setDateOfCollection(date);
452
        repository.setAggregator("OPENAIRE");
453

    
454
        UriComponents uriComponents = UriComponentsBuilder
455
                .fromHttpUrl(baseAddress + "/ds/add/")
456
                .build()
457
                .encode();
458
        String json_repository = Converter.repositoryObjectToJson(repository);
459
        HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
460
        restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
461
    }
462

    
463
    @Override
464
    public void deleteRepositoryInterface(@PathVariable("id") String id){
465
        UriComponents uriComponents = UriComponentsBuilder
466
                .fromHttpUrl(baseAddress + "/ds/api/")
467
                .path("/{id}/")
468
                .build().expand(id).encode();
469
        restTemplate.delete(uriComponents.toUri());
470
    }
471

    
472
    @Override
473
    public RepositoryInterface addRepositoryInterface(@RequestBody String params) throws JSONException {
474

    
475
        JSONObject json_params = new JSONObject(params);
476

    
477
        LOGGER.debug(params);
478
        //TODO iFace parameter from gui. Object to json
479
        String datatype = json_params.getString("datatype");
480
        String repoId = json_params.getString("repoId");
481
        String json_iFace = json_params.getString("iFace");
482
        RepositoryInterface iFace = null;
483

    
484
        ObjectMapper mapper = new ObjectMapper();
485
        try {
486
            iFace = mapper.readValue(json_iFace, RepositoryInterface.class);
487
        } catch (Exception e1) {
488
            LOGGER.debug("Error parsing repository interface ", e1);
489
        }
490

    
491
        return registerRepositoryInterface(repoId,iFace,datatype);
492
    }
493

    
494
    private RepositoryInterface registerRepositoryInterface(String repoId, RepositoryInterface iFace, String datatype) {
495
        Repository e = null;
496
        try {
497
            e = this.getRepositoryById(repoId);
498
            iFace = createRepositoryInterface(e,iFace,datatype);
499
            ObjectMapper mapper = new ObjectMapper();
500

    
501
            String json_interface = Converter.repositoryInterfaceObjectToJson(e,iFace);
502
            LOGGER.debug("iFace equals -> "  + json_interface);
503
            UriComponents uriComponents = UriComponentsBuilder
504
                    .fromHttpUrl(baseAddress + "/ds/api/add/")
505
                    .build()
506
                    .encode();
507

    
508

    
509
            HttpEntity<String> httpEntity = new HttpEntity <String> (json_interface,httpHeaders);
510
            restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
511
            return iFace;
512

    
513
        } catch (JSONException e1) {
514
            LOGGER.debug("Error parsing json ",e1);
515
        }
516
        return null;
517
    }
518

    
519
    @Override
520
    public List<String> getDnetCountries() {
521
        LOGGER.debug("Getting dnet-countries!");
522
        return Converter.readFile("countries.txt");
523
    }
524

    
525
    @Override
526
    public List<String> getTypologies() {
527
        return Converter.readFile("typologies.txt");
528
    }
529

    
530
    @Override
531
    public List<Timezone> getTimezones() {
532
        List<String> timezones =  Converter.readFile("timezones.txt");
533
        return Converter.toTimezones(timezones);
534
    }
535

    
536
    @Override
537
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
538
                                      @RequestParam(value = "managed")  String managed) {
539

    
540
        UriComponents uriComponents = UriComponentsBuilder
541
                .fromHttpUrl(baseAddress + "/ds/manage/")
542
                .queryParam("id",id)
543
                .queryParam("managed",managed)
544
                .build().encode();
545

    
546
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
547
    }
548

    
549
    @Override
550
    public String updateEnglishName(@RequestParam(value = "id")   String id,
551
                                    @RequestParam(value = "englishname")  String englishName) {
552

    
553
        UriComponents uriComponents = UriComponentsBuilder
554
                .fromHttpUrl(baseAddress + "/ds/englishname/")
555
                .queryParam("dsId",id)
556
                .queryParam("englishname",englishName)
557
                .build().encode();
558
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
559

    
560

    
561
    }
562

    
563
    @Override
564
    public String updateLatitude(@RequestParam(value = "id")   String id,
565
                                 @RequestParam(value = "managed")  String latitude) {
566

    
567
        UriComponents uriComponents = UriComponentsBuilder
568
                .fromHttpUrl(baseAddress + "/ds/latitude/")
569
                .queryParam("dsId",id)
570
                .queryParam("latitude",latitude)
571
                .build().encode();
572
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
573
    }
574

    
575
    @Override
576
    public String updateLongitude(@RequestParam(value = "id")   String id,
577
                                  @RequestParam(value = "longitude")  String longitude) {
578

    
579
        UriComponents uriComponents = UriComponentsBuilder
580
                .fromHttpUrl(baseAddress + "/ds/longitude/")
581
                .queryParam("dsId",id)
582
                .queryParam("longitude",longitude)
583
                .build().encode();
584
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
585
    }
586

    
587
    @Override
588
    public String updateOfficialName(@RequestParam(value = "id")   String id,
589
                                     @RequestParam(value = "officialname")  String officialname) {
590

    
591
        UriComponents uriComponents = UriComponentsBuilder
592
                .fromHttpUrl(baseAddress + "/ds/officialname/")
593
                .queryParam("dsId",id)
594
                .queryParam("officialname",officialname)
595
                .build().encode();
596
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
597
    }
598

    
599
    @Override
600
    public String updateTimezone(@RequestParam(value = "id")   String id,
601
                                 @RequestParam(value = "timezone")  String timezone) {
602
        UriComponents uriComponents = UriComponentsBuilder
603
                .fromHttpUrl(baseAddress + "/ds/timezone")
604
                .queryParam("dsId",id)
605
                .queryParam("timezone",timezone)
606
                .build().encode();
607
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
608
    }
609

    
610
    @Override
611
    public String updateTypology(@RequestParam(value = "id")   String id,
612
                                 @RequestParam(value = "typology")  String typology) {
613
        UriComponents uriComponents = UriComponentsBuilder
614
                .fromHttpUrl(baseAddress + "/ds/typology")
615
                .queryParam("dsId",id)
616
                .queryParam("typology",typology)
617
                .build().encode();
618
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
619
    }
620

    
621
    @Override
622
    public String updateLogoUrl(@RequestParam(value = "id")   String id,
623
                                @RequestParam(value = "logoUrl") String logoUrl) {
624
        UriComponents uriComponents = UriComponentsBuilder
625
                .fromHttpUrl(baseAddress + "/ds/logourl")
626
                .queryParam("dsId",id)
627
                .queryParam("logourl",logoUrl)
628
                .build().encode();
629
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
630
    }
631

    
632
    @Override
633
    public String updatePlatform(String id, String platform) {
634
        UriComponents uriComponents = UriComponentsBuilder
635
                .fromHttpUrl(baseAddress + "/ds/platform")
636
                .queryParam("dsId",id)
637
                .queryParam("platform",platform)
638
                .build().encode();
639
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
640
    }
641

    
642
    @Override
643
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String user_email,
644
                                           @PathVariable("page") String page,
645
                                           @PathVariable("size") String size) throws JSONException {
646
        UriComponents uriComponents = UriComponentsBuilder
647
                .fromHttpUrl(baseAddress + "/api/baseurl/")
648
                .path("/{page}/{size}")
649
                .queryParam("userEmail",user_email)
650
                .build().expand(page,size).encode();
651
        return Arrays.asList(restTemplate.getForObject(uriComponents.toUri(), String[].class));
652
    }
653

    
654
    @Override
655
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
656

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

    
674

    
675
        return resultSet;
676
    }
677

    
678
    private Vocabulary getVocabulary(String vocName) {
679

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

    
686

    
687
    @Override
688
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
689

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

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

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

    
713
        return retMap;
714
    }
715

    
716
    @Override
717
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
718

    
719
        LOGGER.debug("Getting datasource classes for mode: " + mode);
720

    
721
        Map<String, String> retMap = new HashMap<String, String>();
722

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

    
740
    }
741

    
742
    @Override
743
    public String getCountryName(String countryCode) {
744
        return inverseCountriesMap.get(countryCode);
745
    }
746

    
747
}
(8-8/10)