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 com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
6
import eu.dnetlib.domain.enabling.Vocabulary;
7
import eu.dnetlib.repo.manager.service.utils.Converter;
8
import eu.dnetlib.domain.data.Repository;
9
import eu.dnetlib.domain.data.RepositoryInterface;
10
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
11
import org.apache.log4j.Logger;
12
import org.json.JSONArray;
13
import org.json.JSONException;
14
import org.json.JSONObject;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.beans.factory.annotation.Value;
17
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
18
import org.springframework.stereotype.Component;
19
import org.springframework.web.bind.annotation.PathVariable;
20
import org.springframework.web.bind.annotation.RequestBody;
21
import org.springframework.web.bind.annotation.RequestParam;
22
import org.springframework.web.client.RestTemplate;
23
import org.springframework.web.util.UriComponents;
24
import org.springframework.web.util.UriComponentsBuilder;
25
import javax.annotation.PostConstruct;
26
import java.sql.Timestamp;
27
import java.text.Normalizer;
28
import java.util.*;
29
import java.util.concurrent.ConcurrentHashMap;
30
import eu.dnetlib.repo.manager.shared.*;
31

    
32
@Component
33
public class RepositoryApiImpl implements RepositoryApi {
34

    
35
    @Value("${api.baseAddress}")
36
    private String baseAddress;
37

    
38
    private RestTemplate restTemplate = null;
39

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

    
42
    private static final Logger LOGGER = Logger.getLogger(RepositoryApiImpl.class);
43

    
44
    @Autowired
45
    private VocabularyLoader vocabularyLoader;
46

    
47
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
48

    
49
    private Map<String, String> countriesMap = new HashMap<>();
50
    private Map<String, String> inverseCountriesMap = new HashMap<>();
51

    
52

    
53
    @PostConstruct
54
    private void init() {
55
        LOGGER.debug("Initialization method of repository api!");
56

    
57
        restTemplate = new RestTemplate();
58
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
59

    
60
        for (String vocName : vocabularyNames) {
61
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
62
        }
63

    
64
        Country[] countries = getCountries();
65
        for (Country c : countries) {
66
            countriesMap.put(c.getName(), c.getCode());
67
            inverseCountriesMap.put(c.getCode(), c.getName());
68
        }
69

    
70

    
71
    }
72

    
73
    @Override
74
    public List<String> testAggregations() throws JSONException {
75

    
76
        int page = 0;
77
        int size = 1000;
78

    
79
        UriComponents uriComponents = UriComponentsBuilder
80
                .fromHttpUrl(baseAddress + "/ds/list/")
81
                .path("/{page}/{size}/")
82
                .build().expand(page, size).encode();
83

    
84
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
85
        List<String> ids = new ArrayList<>();
86
        while (!rs.equals("[]")) {
87

    
88
            ids.addAll(getIdsWithNonEmptyAggregations(rs));
89

    
90
            LOGGER.debug("Checked " + (page + 1) * size + " records!");
91

    
92
            page += 1;
93
            uriComponents = UriComponentsBuilder
94
                    .fromHttpUrl(baseAddress + "/ds/list/")
95
                    .path("/{page}/{size}/")
96
                    .build().expand(page, size).encode();
97
            rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
98
        }
99

    
100
        return ids;
101
    }
102

    
103
    private List<String> getIdsWithNonEmptyAggregations(String rs) throws JSONException {
104

    
105
        JSONArray ids = new JSONArray(rs);
106
        List<String> agg_ids = new ArrayList<>();
107
        for (int i = 0; i < ids.length(); i++) {
108
            String id = ids.getString(i);
109
            Aggregations aggregations = getRepositoryAggregations(id);
110
            if (aggregations.getAggregationHistory() != null)
111
                agg_ids.add(id);
112
        }
113
        return agg_ids;
114
    }
115

    
116
    @Override
117
    public Country[] getCountries() {
118
        UriComponents uriComponents = UriComponentsBuilder
119
                .fromHttpUrl(baseAddress + "/ds/countries")
120
                .build().encode();
121
        return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
122
    }
123

    
124

    
125
    @Override
126
    public List<Repository> getRepositoriesByCountry(@PathVariable("country") String country,
127
                                                     @PathVariable("mode") String mode) throws JSONException {
128

    
129
        LOGGER.debug("Getting repositories by country!");
130
        int page = 0;
131
        int size = 100;
132

    
133
        String countryCode = countriesMap.get(country);
134
        String filterKey = "UNKNOWN";
135
        if (mode.equalsIgnoreCase("opendoar")) {
136
            filterKey = "openaire____::opendoar";
137
        } else if (mode.equalsIgnoreCase("re3data")) {
138
            filterKey = "openaire____::re3data";
139
        } else if (mode.equalsIgnoreCase("jour_aggr")) {
140
            filterKey = "infrastruct_::openaire";
141
        }
142

    
143
        LOGGER.debug("Country code equals : " + countryCode);
144
        LOGGER.debug("Filter mode equals : " + filterKey);
145
        UriComponents uriComponents = UriComponentsBuilder
146
                .fromHttpUrl(baseAddress + "/ds/search/country/")
147
                .path("/{page}/{size}/")
148
                .queryParam("country", countryCode)
149
                .build().expand(page, size).encode();
150

    
151
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
152
        List<Repository> resultSet = new ArrayList<>();
153
        while (!rs.equals("[]")) {
154
            List<Repository> rep = Converter.jsonToRepositoryList(new JSONArray(rs));
155

    
156
            Collection<Repository> repos = this.getRepositoriesByMode(filterKey, rep);
157
            resultSet.addAll(repos);
158

    
159
            page += 1;
160
            uriComponents = UriComponentsBuilder
161
                    .fromHttpUrl(baseAddress + "/ds/search/country/")
162
                    .path("/{page}/{size}/")
163
                    .queryParam("country", countryCode)
164
                    .build().expand(page, size).encode();
165
            rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
166
        }
167
        for (Repository r : resultSet)
168
            r.setCountryName(getCountryName(r.getCountryCode()));
169
        return resultSet;
170
    }
171

    
172

    
173
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
174

    
175
        List<Repository> reps = new ArrayList<>();
176
        for (Repository r : rs) {
177
            if (r.getCollectedFrom().equals(mode))
178
                reps.add(r);
179
        }
180
        return reps;
181
    }
182

    
183
    @Override
184
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
185
                                                  @PathVariable("page") String page,
186
                                                  @PathVariable("size") String size) throws JSONException {
187

    
188
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
189
        UriComponents uriComponents = UriComponentsBuilder
190
                .fromHttpUrl(baseAddress + "/ds/search/registeredby/")
191
                .path("/{page}/{size}/")
192
                .queryParam("registeredBy", userEmail)
193
                .build().expand(page, size).encode();
194

    
195
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
196
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
197
        for (Repository r : repos){
198
         //   r.setInterfaces(this.getRepositoryInterface(r.getId()));
199
            r.setCountryName(getCountryName(r.getCountryCode()));
200
        }
201

    
202
        return repos;
203
    }
204

    
205
    @Override
206
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException {
207

    
208
        UriComponents uriComponents = UriComponentsBuilder
209
                .fromHttpUrl(baseAddress + "/ds/get/")
210
                .path("/{id}/")
211
                .build().expand(id).encode();
212

    
213
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
214
        Repository repo = Converter.jsonToRepositoryObject(new JSONObject(rs));
215
        //repo.setInterfaces(this.getRepositoryInterface(repo.getId()));
216
        if (repo != null)
217
            repo.setCountryName(getCountryName(repo.getCountryCode()));
218
        return repo;
219
    }
220

    
221

    
222
    @Override
223
    public Aggregations getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
224

    
225
        UriComponents uriComponents = UriComponentsBuilder
226
                .fromHttpUrl(baseAddress + "/ds/get/")
227
                .path("/{id}/")
228
                .build().expand(id).encode();
229

    
230
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
231
        JSONObject repository = new JSONObject(rs);
232

    
233
        Aggregations aggregations = new Aggregations();
234

    
235
        try {
236
            aggregations.setAggregationHistory(Converter.getAggregationHistoryFromJson(repository));
237
            aggregations.setLastCollection(Converter.getLastCollectionFromJson(repository));
238
            aggregations.setLastTransformation(Converter.getLastTransformationFromJson(repository));
239
            return aggregations;
240
        } catch (JSONException e) {
241
            LOGGER.debug("JSON aggregation exception ", e);
242
            throw e;
243
        }
244

    
245
    }
246

    
247
    @Override
248
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
249
                                                  @PathVariable("page") String page,
250
                                                  @PathVariable("size") String size) throws JSONException {
251
        UriComponents uriComponents = UriComponentsBuilder
252
                .fromHttpUrl(baseAddress + "/ds/search/name/")
253
                .path("/{page}/{size}")
254
                .queryParam("name", name)
255
                .build().expand(page, size).encode();
256

    
257
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
258
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
259
        for (Repository r : repos){
260
           // r.setInterfaces(this.getRepositoryInterface(r.getId()));
261
            r.setCountryName(getCountryName(r.getCountryCode()));
262
        }
263
        return repos;
264
    }
265

    
266
    @Override
267
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
268

    
269
        UriComponents uriComponents = UriComponentsBuilder
270
                .fromHttpUrl(baseAddress + "/ds/api/")
271
                .path("/{id}/")
272
                .build().expand(id).encode();
273

    
274
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
275
        return Converter.jsonToRepositoryInterfaceList(new JSONArray(rs));
276
    }
277

    
278
    @Override
279
    public void addRepository(@RequestBody String params) throws Exception {
280

    
281
        JSONObject json_params = new JSONObject(params);
282
        String datatype = json_params.getString("datatype");
283
        String json_repository = json_params.getString("repository");
284
        Repository repository = null;
285
        ObjectMapper mapper = new ObjectMapper();
286
        mapper.disable(DeserializationFeature.FAIL_ON_UNK‌​NOWN_PROPERTIES);
287
        try {
288
            LOGGER.debug("repository -> " + json_repository);
289
            repository = mapper.readValue(json_repository, Repository.class);
290
        } catch (Exception e) {
291
            LOGGER.debug("Error parsing repository ", e);
292
            throw  e;
293
        }
294

    
295
        repository = this.setRepositoryFeatures(datatype,repository);
296

    
297
        LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
298
        if (!datatype.equalsIgnoreCase("opendoar") && !datatype.equalsIgnoreCase("re3data")) {
299
            if (datatype.equalsIgnoreCase("journal") || datatype.equalsIgnoreCase("aggregator")) {
300
                LOGGER.debug("looking if " + datatype + " " + repository.getOfficialName() + " is already in datasources");
301
                if (getRepositoryById(repository.getId()) != null) {
302
                    String retMessage = datatype + " '" + repository.getOfficialName() + "' is already in datasources.";
303
                    repository.getInterfaces().clear();
304
                    LOGGER.debug(retMessage);
305
                } else {
306
                    LOGGER.debug(datatype + " " + repository.getOfficialName() + " is not in datasources. Inserting..");
307
                    this.storeRepository(repository);
308
                }
309
            }
310
        } else {
311
            this.updateRegisteredByValue(repository.getId(),repository.getRegisteredBy());
312
        }
313

    
314
        LOGGER.debug("Inserting Interfaces");
315
        Iterator var11 = repository.getInterfaces().iterator();
316

    
317
        while (var11.hasNext()) {
318
            RepositoryInterface iFace = (RepositoryInterface) var11.next();
319
            if (!iFace.getBaseUrl().isEmpty() && !iFace.getDesiredCompatibilityLevel().isEmpty()) {
320
                if (iFace.getId() != null && !iFace.getId().isEmpty()) {
321
                    LOGGER.debug("updating iface..");
322
                    this.updateInterface(datatype,iFace);
323
                    LOGGER.debug("updated successfully");
324
                } else {
325
                    LOGGER.debug("adding new iface..");
326
                    this.registerRepositoryInterface(repository.getId(),iFace,datatype);
327
                }
328
            }
329
        }
330
    }
331

    
332
    private void updateRegisteredByValue(String id, String registeredBy) {
333

    
334
        LOGGER.debug("Updating registered by value with  : " + registeredBy );
335
        UriComponents uriComponents = UriComponentsBuilder
336
                .fromHttpUrl(baseAddress + "/ds/registeredby/")
337
                .queryParam("dsId",id)
338
                .queryParam("registeredBy", registeredBy)
339
                .build()
340
                .encode();
341

    
342
        restTemplate.postForObject(uriComponents.toUri(), null,String.class);
343
    }
344

    
345
    private Repository setRepositoryFeatures(String datatype, Repository repository) {
346

    
347
        //TODO update map
348
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
349

    
350
        repository.setActivationId(UUID.randomUUID().toString());
351
        // repo.setRegisteredBy((String) session.get(LocalVocabularies.loggedInField));
352

    
353
        if (datatype.equals("opendoar") || datatype.equals("re3data")) {
354
            repository.setProvenanceActionClass("sysimport:crosswalk:entityregistry");
355
        } else if (datatype.equals("journal")) {
356
            repository.setProvenanceActionClass("user:insert");
357
            repository.setCollectedFrom("infrastruct_::openaire");
358
            if (repository.getIssn() != null && repository.getIssn().length() == 0)
359
                repository.setIssn(com.unboundid.util.Base64.encode(repository.getOfficialName()).substring(0, 8));
360
            repository.setId("openaire____::issn" + repository.getIssn());
361
            repository.setNamespacePrefix("issn" + repository.getIssn());
362
        } else if (datatype.equals("aggregator")) {
363
            repository.setProvenanceActionClass("user:insert");
364
            repository.setCollectedFrom("infrastruct_::openaire");
365
            repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
366
            repository.setNamespacePrefix(Normalizer.normalize(repository.getOfficialName().toLowerCase().replace(" ", "_"), Normalizer.Form.NFD).replaceAll("[^a-zA-Z0-9]", ""));
367
            if (repository.getNamespacePrefix().length() > 12) {
368
                repository.setNamespacePrefix(repository.getNamespacePrefix().substring(0, 12));
369
            } else {
370
                while (repository.getNamespacePrefix().length() < 12)
371
                    repository.setNamespacePrefix(repository.getNamespacePrefix().concat("_"));
372
            }
373
        }
374
        return repository;
375
    }
376

    
377
    private void updateInterface(String datatype,RepositoryInterface iFace) {
378
        //TODO call update base url
379
        //((DatasourceManagerService) this.dmService.getService()).updateBaseUrl(repo.getId(), iFace.getId(), iFace.getBaseUrl());
380

    
381
        if (!iFace.getAccessSet().isEmpty()) {
382
            LOGGER.debug("set not empty: " + iFace.getAccessSet());
383
            //TODO call update method for access params
384
            // ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "set", iFace.getAccessSet(), false);
385
        } else {
386
            //TODO call deleteAccessParamOrExtraField
387
            //((DatasourceManagerService) this.dmService.getService()).deleteAccessParamOrExtraField(repo.getId(), iFace.getId(), "set");
388
        }
389
        //TODO update content description
390
        //((DatasourceManagerService) this.dmService.getService()).updateContentDescription(repo.getId(), iFace.getId(), "metadata");
391
        if (datatype.equals("re3data")) {
392
            //TODO call update access params
393
            //  ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_datacite", false);
394
            iFace.setAccessFormat("oai_datacite");
395
        } else {
396
            //TODO call update access params
397
            //((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_dc", false);
398
            iFace.setAccessFormat("oai_dc");
399
        }
400

    
401
    }
402

    
403
    private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
404

    
405
        iFace.setContentDescription("metadata");
406
        iFace.setCompliance("UNKNOWN");
407
        if (datatype.equals("re3data")) {
408
            iFace.setAccessFormat("oai_datacite");
409
        } else {
410
            iFace.setAccessFormat("oai_dc");
411
        }
412

    
413
        if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty()) {
414
            iFace.setTypology(repo.getDatasourceClass());
415
        } else if (datatype.equalsIgnoreCase("journal")) {
416
            iFace.setTypology("pubsrepository::journal");
417
        } else if (datatype.equalsIgnoreCase("aggregator")) {
418
            iFace.setTypology("aggregator::pubsrepository::unknown");
419
        } else if (datatype.equalsIgnoreCase("opendoar")) {
420
            iFace.setTypology("pubsrepository::unknown");
421
        } else if (datatype.equalsIgnoreCase("re3data")) {
422
            iFace.setTypology("datarepository::unknown");
423
        }
424

    
425
        iFace.setRemovable(true);
426
        iFace.setAccessProtocol("oai");
427
        iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
428
        iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
429
        if (iFace.getAccessSet().isEmpty()) {
430
            LOGGER.debug("set is empty: " + iFace.getAccessSet());
431
            iFace.removeAccessSet();
432
        }
433
        return iFace;
434
    }
435

    
436
    private void storeRepository(Repository repository) throws JSONException {
437

    
438
        Date utilDate = new Date();
439
        Timestamp date = new Timestamp(utilDate.getTime());
440
        repository.setDateOfCollection(date);
441
        repository.setAggregator("OPENAIRE");
442

    
443
        UriComponents uriComponents = UriComponentsBuilder
444
                .fromHttpUrl(baseAddress + "/ds/add/")
445
                .build()
446
                .encode();
447
        try {
448
            LOGGER.debug("Repository equals : " + Converter.repositoryObjectToJson(repository));
449
        }catch (Exception e){
450
            LOGGER.debug("JSON exception ", e);
451
            throw e;
452
        }
453
        restTemplate.postForObject(uriComponents.toUri(),Converter.repositoryObjectToJson(repository),String.class);
454
    }
455

    
456
    @Override
457
    public void deleteRepositoryInterface(@PathVariable("id") String id){
458
        UriComponents uriComponents = UriComponentsBuilder
459
                .fromHttpUrl(baseAddress + "/ds/api/")
460
                .path("/{id}/")
461
                .build().expand(id).encode();
462
        restTemplate.delete(uriComponents.toUri());
463
    }
464

    
465
    @Override
466
    public RepositoryInterface addRepositoryInterface(@RequestBody String params) throws JSONException {
467

    
468
        JSONObject json_params = new JSONObject(params);
469
        String datatype = json_params.getString("datatype");
470
        String repoId = json_params.getString("repoId");
471
        String json_iFace = json_params.getString("iFace");
472
        RepositoryInterface iFace = null;
473

    
474
        ObjectMapper mapper = new ObjectMapper();
475
        try {
476
            iFace = mapper.readValue(json_iFace, RepositoryInterface.class);
477
        } catch (Exception e1) {
478
            LOGGER.debug("Error parsing repository interface ", e1);
479
        }
480

    
481
        return registerRepositoryInterface(repoId,iFace,datatype);
482
    }
483

    
484
    private RepositoryInterface registerRepositoryInterface(String repoId, RepositoryInterface iFace, String datatype) {
485
        Repository e = null;
486
        try {
487
            e = this.getRepositoryById(repoId);
488
            iFace = createRepositoryInterface(e,iFace,datatype);
489

    
490
            LOGGER.debug("iFace equals : " + Converter.repositoryInterfaceObjectToJson(e,iFace));
491

    
492
            UriComponents uriComponents = UriComponentsBuilder
493
                    .fromHttpUrl(baseAddress + "/ds/api/add/")
494
                    .build()
495
                    .encode();
496
            String rs =  restTemplate.postForObject(uriComponents.toUri(), Converter.repositoryInterfaceObjectToJson(e,iFace),String.class);
497
            return Converter.jsonToRepositoryInterfaceObject(new JSONArray(rs).getJSONObject(0));
498

    
499
        } catch (JSONException e1) {
500
            LOGGER.debug("Error parsing json ",e1);
501
        }
502
        return null;
503
    }
504

    
505
    @Override
506
    public List<String> getDnetCountries() {
507
        LOGGER.debug("Getting dnet-countries!");
508
        return Converter.readFile("countries.txt");
509
    }
510

    
511
    @Override
512
    public List<String> getTypologies() {
513
        return Converter.readFile("typologies.txt");
514
    }
515

    
516
    @Override
517
    public List<Timezone> getTimezones() {
518
        List<String> timezones =  Converter.readFile("timezones.txt");
519
        return Converter.toTimezones(timezones);
520
    }
521

    
522
    @Override
523
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
524
                                      @RequestParam(value = "managed")  String managed) {
525

    
526
        UriComponents uriComponents = UriComponentsBuilder
527
                .fromHttpUrl(baseAddress + "/ds/manage/")
528
                .queryParam("id",id)
529
                .queryParam("managed",managed)
530
                .build().encode();
531

    
532
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
533
    }
534

    
535
    @Override
536
    public String updateEnglishName(@RequestParam(value = "id")   String id,
537
                                    @RequestParam(value = "englishname")  String englishName) {
538

    
539
        UriComponents uriComponents = UriComponentsBuilder
540
                .fromHttpUrl(baseAddress + "/ds/englishname/")
541
                .queryParam("dsId",id)
542
                .queryParam("englishname",englishName)
543
                .build().encode();
544
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
545

    
546

    
547
    }
548

    
549
    @Override
550
    public String updateLatitude(@RequestParam(value = "id")   String id,
551
                                 @RequestParam(value = "managed")  String latitude) {
552

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

    
561
    @Override
562
    public String updateLongitude(@RequestParam(value = "id")   String id,
563
                                  @RequestParam(value = "longitude")  String longitude) {
564

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

    
573
    @Override
574
    public String updateOfficialName(@RequestParam(value = "id")   String id,
575
                                     @RequestParam(value = "officialname")  String officialname) {
576

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

    
585
    @Override
586
    public String updateTimezone(@RequestParam(value = "id")   String id,
587
                                 @RequestParam(value = "timezone")  String timezone) {
588
        UriComponents uriComponents = UriComponentsBuilder
589
                .fromHttpUrl(baseAddress + "/ds/timezone")
590
                .queryParam("dsId",id)
591
                .queryParam("timezone",timezone)
592
                .build().encode();
593
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
594
    }
595

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

    
607
    @Override
608
    public String updateLogoUrl(@RequestParam(value = "id")   String id,
609
                                @RequestParam(value = "logoUrl") String logoUrl) {
610
        UriComponents uriComponents = UriComponentsBuilder
611
                .fromHttpUrl(baseAddress + "/ds/logourl")
612
                .queryParam("dsId",id)
613
                .queryParam("logourl",logoUrl)
614
                .build().encode();
615
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
616
    }
617

    
618
    @Override
619
    public String updatePlatform(String id, String platform) {
620
        UriComponents uriComponents = UriComponentsBuilder
621
                .fromHttpUrl(baseAddress + "/ds/platform")
622
                .queryParam("dsId",id)
623
                .queryParam("platform",platform)
624
                .build().encode();
625
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
626
    }
627

    
628
    @Override
629
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String user_email,
630
                                           @PathVariable("page") String page,
631
                                           @PathVariable("size") String size) throws JSONException {
632
        UriComponents uriComponents = UriComponentsBuilder
633
                .fromHttpUrl(baseAddress + "/api/baseurl/")
634
                .path("/{page}/{size}")
635
                .queryParam("userEmail",user_email)
636
                .build().expand(page,size).encode();
637
        return Arrays.asList(restTemplate.getForObject(uriComponents.toUri(), String[].class));
638
    }
639

    
640
    @Override
641
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
642

    
643
        List<String> resultSet = new ArrayList<>();
644
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
645
            if (mode.equalsIgnoreCase("aggregator")) {
646
                if (entry.getKey().contains("aggregator"))
647
                    resultSet.add(entry.getValue());
648
            } else if (mode.equalsIgnoreCase("journal")) {
649
                if (entry.getKey().contains("journal"))
650
                    resultSet.add(entry.getValue());
651
            } else if (mode.equalsIgnoreCase("opendoar")) {
652
                if (entry.getKey().contains("pubsrepository"))
653
                    resultSet.add(entry.getValue());
654
            } else if (mode.equalsIgnoreCase("re3data")) {
655
                if (entry.getKey().contains("datarepository"))
656
                    resultSet.add(entry.getValue());
657
            }
658
        }
659

    
660

    
661
        return resultSet;
662
    }
663

    
664
    private Vocabulary getVocabulary(String vocName) {
665

    
666
        if (!vocabularyMap.containsKey(vocName)) {
667
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
668
        }
669
        return vocabularyMap.get(vocName);
670
    }
671

    
672

    
673
    @Override
674
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
675

    
676
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
677
        Map<String, String> retMap = new HashMap<String, String>();
678

    
679
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
680
        boolean foundData = false;
681
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
682
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
683
                return compatibilityClasses;
684
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
685
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
686
                    retMap.put(entry.getKey(), entry.getValue());
687
                    foundData = true;
688
                }
689
            } else {
690
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
691
                    retMap.put(entry.getKey(), entry.getValue());
692
            }
693
        }
694

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

    
699
        return retMap;
700
    }
701

    
702
    @Override
703
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
704

    
705
        LOGGER.debug("Getting datasource classes for mode: " + mode);
706

    
707
        Map<String, String> retMap = new HashMap<String, String>();
708

    
709
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
710
            if (mode.equalsIgnoreCase("aggregator")) {
711
                if (entry.getKey().contains("aggregator"))
712
                    retMap.put(entry.getKey(), entry.getValue());
713
            } else if (mode.equalsIgnoreCase("journal")) {
714
                if (entry.getKey().contains("journal"))
715
                    retMap.put(entry.getKey(), entry.getValue());
716
            } else if (mode.equalsIgnoreCase("opendoar")) {
717
                if (entry.getKey().contains("pubsrepository"))
718
                    retMap.put(entry.getKey(), entry.getValue());
719
            } else if (mode.equalsIgnoreCase("re3data")) {
720
                if (entry.getKey().contains("datarepository"))
721
                    retMap.put(entry.getKey(), entry.getValue());
722
            }
723
        }
724
        return retMap;
725

    
726
    }
727

    
728
    @Override
729
    public String getCountryName(String countryCode) {
730
        return inverseCountriesMap.get(countryCode);
731
    }
732

    
733
}
(8-8/10)