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 javax.ws.rs.Path;
33
import javax.ws.rs.QueryParam;
34
import java.io.IOException;
35
import java.sql.Timestamp;
36
import java.text.Normalizer;
37
import java.util.*;
38
import java.util.concurrent.ConcurrentHashMap;
39

    
40
@Component
41
public class RepositoryApiImpl implements RepositoryApi {
42

    
43
    @Value("${api.baseAddress}")
44
    private String baseAddress;
45

    
46
    private RestTemplate restTemplate = null;
47

    
48
    private HttpHeaders httpHeaders;
49

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

    
52
    private static final Logger LOGGER = Logger.getLogger(RepositoryApiImpl.class);
53

    
54
    @Autowired
55
    private VocabularyLoader vocabularyLoader;
56

    
57
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
58

    
59
    private Map<String, String> countriesMap = new HashMap<>();
60
    private Map<String, String> inverseCountriesMap = new HashMap<>();
61

    
62

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

    
67
        restTemplate = new RestTemplate();
68
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
69

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

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

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

    
83

    
84
    }
85

    
86
    @Override
87
    public List<String> testAggregations() throws JSONException {
88

    
89
        int page = 0;
90
        int size = 1000;
91

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

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

    
101
            ids.addAll(getIdsWithNonEmptyAggregations(rs));
102

    
103
            LOGGER.debug("Checked " + (page + 1) * size + " records!");
104

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

    
113
        return ids;
114
    }
115

    
116
    private List<String> getIdsWithNonEmptyAggregations(String rs) throws JSONException {
117

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

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

    
137

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

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

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

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

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

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

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

    
185
        return resultSet;
186
    }
187

    
188

    
189
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
190

    
191
        List<Repository> reps = new ArrayList<>();
192
        for (Repository r : rs) {
193
            if (r.getCollectedFrom().equals(mode))
194
                reps.add(r);
195
        }
196
        return reps;
197
    }
198

    
199
    @Override
200
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
201
                                                  @PathVariable("page") String page,
202
                                                  @PathVariable("size") String size) throws JSONException {
203

    
204
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
205
        UriComponents uriComponents = UriComponentsBuilder
206
                .fromHttpUrl(baseAddress + "/ds/search/registeredby/")
207
                .path("/{page}/{size}/")
208
                .queryParam("registeredBy", userEmail)
209
                .build().expand(page, size).encode();
210

    
211
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
212
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
213
        for (Repository r : repos){
214
            r.setInterfaces(this.getRepositoryInterface(r.getId()));
215
            r.setCountryName(getCountryName(r.getCountryCode()));
216
        }
217

    
218
        return repos;
219
    }
220

    
221
    @Override
222
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException {
223

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

    
229
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
230
        Repository repo = Converter.jsonToRepositoryObject(new JSONObject(rs));
231
        if (repo != null) {
232
            repo.setCountryName(getCountryName(repo.getCountryCode()));
233
            repo.setInterfaces(this.getRepositoryInterface(repo.getId()));
234
        }
235
        return repo;
236
    }
237

    
238

    
239
    @Override
240
    public Aggregations getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
241

    
242
        UriComponents uriComponents = UriComponentsBuilder
243
                .fromHttpUrl(baseAddress + "/ds/get/")
244
                .path("/{id}/")
245
                .build().expand(id).encode();
246

    
247
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
248
        JSONObject repository = new JSONObject(rs);
249

    
250
        Aggregations aggregations = new Aggregations();
251

    
252
        try {
253
            aggregations.setAggregationHistory(Converter.getAggregationHistoryFromJson(repository));
254
            aggregations.setLastCollection(Converter.getLastCollectionFromJson(repository));
255
            aggregations.setLastTransformation(Converter.getLastTransformationFromJson(repository));
256
            return aggregations;
257
        } catch (JSONException e) {
258
            LOGGER.debug("JSON aggregation exception ", e);
259
            throw e;
260
        }
261

    
262
    }
263

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

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

    
283
    @Override
284
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
285

    
286
        UriComponents uriComponents = UriComponentsBuilder
287
                .fromHttpUrl(baseAddress + "/ds/api/")
288
                .path("/{id}/")
289
                .build().expand(id).encode();
290

    
291
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
292
        return Converter.jsonToRepositoryInterfaceList(new JSONArray(rs));
293
    }
294

    
295
    @Override
296
    public void addRepository(@RequestParam("datatype") String datatype,
297
                              @RequestBody Repository repository) throws Exception {
298

    
299
        /*JSONObject json_params = new JSONObject(params);
300
        String datatype = json_params.getString("datatype");
301
        String json_repository = json_params.getString("repository");
302
        Repository repository = null;*/
303
        ObjectMapper mapper = new ObjectMapper();
304
        mapper.disable(DeserializationFeature.FAIL_ON_UNK‌​NOWN_PROPERTIES);
305
        try {
306
            String json_repo = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repository);
307
            LOGGER.debug("repository -> " + json_repo);
308
          //  repository = mapper.readValue(json_repository, Repository.class);
309
        } catch (Exception e) {
310
            LOGGER.debug("Error parsing repository ", e);
311
            throw  e;
312
        }
313
        repository = this.setRepositoryFeatures(datatype,repository);
314

    
315
        LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
316
        if (!datatype.equalsIgnoreCase("opendoar") && !datatype.equalsIgnoreCase("re3data")) {
317
            if (datatype.equalsIgnoreCase("journal") || datatype.equalsIgnoreCase("aggregator")) {
318
                LOGGER.debug("looking if " + datatype + " " + repository.getOfficialName() + " is already in datasources");
319
                if (getRepositoryById(repository.getId()) != null) {
320
                    String retMessage = datatype + " '" + repository.getOfficialName() + "' is already in datasources.";
321
                    repository.getInterfaces().clear();
322
                    LOGGER.debug(retMessage);
323
                } else {
324
                    LOGGER.debug(datatype + " " + repository.getOfficialName() + " is not in datasources. Inserting..");
325
                    this.storeRepository(repository);
326
                }
327
            }
328
        } else {
329
            this.updateRepository(repository);
330
        }
331

    
332
        LOGGER.debug("Inserting Interfaces");
333
        Iterator var11 = repository.getInterfaces().iterator();
334

    
335
        while (var11.hasNext()) {
336
            RepositoryInterface iFace = (RepositoryInterface) var11.next();
337
            if (!iFace.getBaseUrl().isEmpty() && !iFace.getDesiredCompatibilityLevel().isEmpty()) {
338
                if (iFace.getId() != null && !iFace.getId().isEmpty()) {
339
                    LOGGER.debug("updating iface..");
340
                    this.updateInterface(datatype,iFace);
341
                    LOGGER.debug("updated successfully");
342
                } else {
343
                    LOGGER.debug("adding new iface..");
344
                    this.registerRepositoryInterface(repository.getId(),iFace,datatype);
345
                }
346
            }
347
        }
348
    }
349

    
350
    private void updateRepository(Repository repository) {
351
        this.updateRegisteredByValue(repository.getId(),repository.getRegisteredBy());
352
        this.updateEnglishName(repository.getId(),repository.getEnglishName());
353
        this.updateLogoUrl(repository.getId(),repository.getLogoUrl());
354
        this.updateTimezone(repository.getId(), String.valueOf(repository.getTimezone()));
355
        //TODO update datasource type
356
    }
357

    
358
    private void updateRegisteredByValue(String id, String registeredBy) {
359

    
360
        LOGGER.debug("Updating registered by value with  : " + registeredBy );
361
        UriComponents uriComponents = UriComponentsBuilder
362
                .fromHttpUrl(baseAddress + "/ds/registeredby/")
363
                .queryParam("dsId",id)
364
                .queryParam("registeredBy", registeredBy)
365
                .build()
366
                .encode();
367

    
368
        restTemplate.postForObject(uriComponents.toUri(), null,String.class);
369
    }
370

    
371
    private Repository setRepositoryFeatures(String datatype, Repository repository) {
372

    
373
        //TODO update map
374
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
375

    
376
        repository.setActivationId(UUID.randomUUID().toString());
377
        // repo.setRegisteredBy((String) session.get(LocalVocabularies.loggedInField));
378

    
379
        if (datatype.equals("opendoar") || datatype.equals("re3data")) {
380
            repository.setProvenanceActionClass("sysimport:crosswalk:entityregistry");
381
        } else if (datatype.equals("journal")) {
382
            repository.setProvenanceActionClass("user:insert");
383
            repository.setCollectedFrom("infrastruct_::openaire");
384
            if (repository.getIssn() != null && repository.getIssn().length() == 0)
385
                repository.setIssn(com.unboundid.util.Base64.encode(repository.getOfficialName()).substring(0, 8));
386
            repository.setId("openaire____::issn" + repository.getIssn());
387
            repository.setNamespacePrefix("issn" + repository.getIssn());
388
        } else if (datatype.equals("aggregator")) {
389
            repository.setProvenanceActionClass("user:insert");
390
            repository.setCollectedFrom("infrastruct_::openaire");
391
            repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
392
            repository.setNamespacePrefix(Normalizer.normalize(repository.getOfficialName().toLowerCase().replace(" ", "_"), Normalizer.Form.NFD).replaceAll("[^a-zA-Z0-9]", ""));
393
            if (repository.getNamespacePrefix().length() > 12) {
394
                repository.setNamespacePrefix(repository.getNamespacePrefix().substring(0, 12));
395
            } else {
396
                while (repository.getNamespacePrefix().length() < 12)
397
                    repository.setNamespacePrefix(repository.getNamespacePrefix().concat("_"));
398
            }
399
        }
400
        return repository;
401
    }
402

    
403
    private void updateInterface(String datatype,RepositoryInterface iFace) {
404
        //TODO call update base url
405
        //((DatasourceManagerService) this.dmService.getService()).updateBaseUrl(repo.getId(), iFace.getId(), iFace.getBaseUrl());
406
        if (!iFace.getAccessSet().isEmpty()) {
407
            LOGGER.debug("set not empty: " + iFace.getAccessSet());
408
            //TODO call update method for access params
409
            // ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "set", iFace.getAccessSet(), false);
410
        } else {
411
            //TODO call deleteAccessParamOrExtraField
412
            //((DatasourceManagerService) this.dmService.getService()).deleteAccessParamOrExtraField(repo.getId(), iFace.getId(), "set");
413
        }
414
        //TODO update content description
415
        //((DatasourceManagerService) this.dmService.getService()).updateContentDescription(repo.getId(), iFace.getId(), "metadata");
416
        if (datatype.equals("re3data")) {
417
            //TODO call update access params
418
            //  ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_datacite", false);
419
            iFace.setAccessFormat("oai_datacite");
420
        } else {
421
            //TODO call update access params
422
            //((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_dc", false);
423
            iFace.setAccessFormat("oai_dc");
424
        }
425

    
426
    }
427

    
428
    private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
429

    
430
        iFace.setContentDescription("metadata");
431
        iFace.setCompliance("UNKNOWN");
432
        if (datatype.equals("re3data")) {
433
            iFace.setAccessFormat("oai_datacite");
434
        } else {
435
            iFace.setAccessFormat("oai_dc");
436
        }
437

    
438
        if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty()) {
439
            iFace.setTypology(repo.getDatasourceClass());
440
        } else if (datatype.equalsIgnoreCase("journal")) {
441
            iFace.setTypology("pubsrepository::journal");
442
        } else if (datatype.equalsIgnoreCase("aggregator")) {
443
            iFace.setTypology("aggregator::pubsrepository::unknown");
444
        } else if (datatype.equalsIgnoreCase("opendoar")) {
445
            iFace.setTypology("pubsrepository::unknown");
446
        } else if (datatype.equalsIgnoreCase("re3data")) {
447
            iFace.setTypology("datarepository::unknown");
448
        }
449

    
450
        iFace.setRemovable(true);
451
        iFace.setAccessProtocol("oai");
452
        iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
453
       // iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
454
        if (iFace.getAccessSet().isEmpty()) {
455
            LOGGER.debug("set is empty: " + iFace.getAccessSet());
456
            iFace.removeAccessSet();
457
        }
458
        return iFace;
459
    }
460

    
461
    private void storeRepository(Repository repository) throws JSONException {
462

    
463
        Date utilDate = new Date();
464
        Timestamp date = new Timestamp(utilDate.getTime());
465
        repository.setDateOfCollection(date);
466
        repository.setAggregator("OPENAIRE");
467

    
468
        UriComponents uriComponents = UriComponentsBuilder
469
                .fromHttpUrl(baseAddress + "/ds/add/")
470
                .build()
471
                .encode();
472
        String json_repository = Converter.repositoryObjectToJson(repository);
473
        HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
474
        restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
475
    }
476

    
477
    @Override
478
    public void deleteRepositoryInterface(@PathVariable("id") String id){
479
        UriComponents uriComponents = UriComponentsBuilder
480
                .fromHttpUrl(baseAddress + "/ds/api/")
481
                .path("/{id}/")
482
                .build().expand(id).encode();
483
        restTemplate.delete(uriComponents.toUri());
484
    }
485

    
486
    @Override
487
    public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
488
                                                      @RequestParam("repoId") String repoId,
489
                                                      @RequestBody RepositoryInterface repositoryInterface) throws JSONException {
490

    
491
     /*   JSONObject json_params = new JSONObject(params);
492
       // LOGGER.debug(params);
493
        //TODO iFace parameter from gui. Object to json
494
        String datatype = json_params.getString("datatype");
495
        String repoId = json_params.getString("repoId");
496
        String json_iFace = json_params.getString("iFace");
497
        RepositoryInterface iFace = null;
498

    
499
        ObjectMapper mapper = new ObjectMapper();
500
        try {
501
            iFace = mapper.readValue(json_iFace, RepositoryInterface.class);
502
        } catch (Exception e1) {
503
            LOGGER.debug("Error parsing repository interface ", e1);
504
        }*/
505
        return registerRepositoryInterface(repoId,repositoryInterface,datatype);
506
    }
507

    
508
    private RepositoryInterface registerRepositoryInterface(String repoId, RepositoryInterface iFace, String datatype) {
509
        Repository e = null;
510
        try {
511
            e = this.getRepositoryById(repoId);
512
            iFace = createRepositoryInterface(e,iFace,datatype);
513
            ObjectMapper mapper = new ObjectMapper();
514

    
515
            String json_interface = Converter.repositoryInterfaceObjectToJson(e,iFace);
516
            LOGGER.debug("iFace equals -> "  + json_interface);
517
            UriComponents uriComponents = UriComponentsBuilder
518
                    .fromHttpUrl(baseAddress + "/ds/api/add/")
519
                    .build()
520
                    .encode();
521

    
522

    
523
            HttpEntity<String> httpEntity = new HttpEntity <String> (json_interface,httpHeaders);
524
            restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
525
            return iFace;
526

    
527
        } catch (JSONException e1) {
528
            LOGGER.debug("Error parsing json ",e1);
529
        }
530
        return null;
531
    }
532

    
533
    @Override
534
    public List<String> getDnetCountries() {
535
        LOGGER.debug("Getting dnet-countries!");
536
        return Converter.readFile("countries.txt");
537
    }
538

    
539
    @Override
540
    public List<String> getTypologies() {
541
        return Converter.readFile("typologies.txt");
542
    }
543

    
544
    @Override
545
    public List<Timezone> getTimezones() {
546
        List<String> timezones =  Converter.readFile("timezones.txt");
547
        return Converter.toTimezones(timezones);
548
    }
549

    
550
    @Override
551
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
552
                                      @RequestParam(value = "managed")  String managed) {
553

    
554
        UriComponents uriComponents = UriComponentsBuilder
555
                .fromHttpUrl(baseAddress + "/ds/manage/")
556
                .queryParam("id",id)
557
                .queryParam("managed",managed)
558
                .build().encode();
559

    
560
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
561
    }
562

    
563
    @Override
564
    public String updateEnglishName(@RequestParam(value = "id")   String id,
565
                                    @RequestParam(value = "englishname")  String englishName) {
566

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

    
574

    
575
    }
576

    
577
    @Override
578
    public String updateLatitude(@RequestParam(value = "id")   String id,
579
                                 @RequestParam(value = "managed")  String latitude) {
580

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

    
589
    @Override
590
    public String updateLongitude(@RequestParam(value = "id")   String id,
591
                                  @RequestParam(value = "longitude")  String longitude) {
592

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

    
601
    @Override
602
    public String updateOfficialName(@RequestParam(value = "id")   String id,
603
                                     @RequestParam(value = "officialname")  String officialname) {
604

    
605
        UriComponents uriComponents = UriComponentsBuilder
606
                .fromHttpUrl(baseAddress + "/ds/officialname/")
607
                .queryParam("dsId",id)
608
                .queryParam("officialname",officialname)
609
                .build().encode();
610
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
611
    }
612

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

    
624
    @Override
625
    public String updateTypology(@RequestParam(value = "id")   String id,
626
                                 @RequestParam(value = "typology")  String typology) {
627
        UriComponents uriComponents = UriComponentsBuilder
628
                .fromHttpUrl(baseAddress + "/ds/typology")
629
                .queryParam("dsId",id)
630
                .queryParam("typology",typology)
631
                .build().encode();
632
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
633
    }
634

    
635
    @Override
636
    public String updateLogoUrl(@RequestParam(value = "id")   String id,
637
                                @RequestParam(value = "logoUrl") String logoUrl) {
638
        UriComponents uriComponents = UriComponentsBuilder
639
                .fromHttpUrl(baseAddress + "/ds/logourl")
640
                .queryParam("dsId",id)
641
                .queryParam("logourl",logoUrl)
642
                .build().encode();
643
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
644
    }
645

    
646
    @Override
647
    public String updatePlatform(String id, String platform) {
648
        UriComponents uriComponents = UriComponentsBuilder
649
                .fromHttpUrl(baseAddress + "/ds/platform")
650
                .queryParam("dsId",id)
651
                .queryParam("platform",platform)
652
                .build().encode();
653
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
654
    }
655

    
656
    @Override
657
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String user_email,
658
                                           @PathVariable("page") String page,
659
                                           @PathVariable("size") String size) throws JSONException {
660
        UriComponents uriComponents = UriComponentsBuilder
661
                .fromHttpUrl(baseAddress + "/api/baseurl/")
662
                .path("/{page}/{size}")
663
                .queryParam("userEmail",user_email)
664
                .build().expand(page,size).encode();
665
        return Arrays.asList(restTemplate.getForObject(uriComponents.toUri(), String[].class));
666
    }
667

    
668
    @Override
669
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
670

    
671
        List<String> resultSet = new ArrayList<>();
672
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
673
            if (mode.equalsIgnoreCase("aggregator")) {
674
                if (entry.getKey().contains("aggregator"))
675
                    resultSet.add(entry.getValue());
676
            } else if (mode.equalsIgnoreCase("journal")) {
677
                if (entry.getKey().contains("journal"))
678
                    resultSet.add(entry.getValue());
679
            } else if (mode.equalsIgnoreCase("opendoar")) {
680
                if (entry.getKey().contains("pubsrepository"))
681
                    resultSet.add(entry.getValue());
682
            } else if (mode.equalsIgnoreCase("re3data")) {
683
                if (entry.getKey().contains("datarepository"))
684
                    resultSet.add(entry.getValue());
685
            }
686
        }
687

    
688

    
689
        return resultSet;
690
    }
691

    
692
    private Vocabulary getVocabulary(String vocName) {
693

    
694
        if (!vocabularyMap.containsKey(vocName)) {
695
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
696
        }
697
        return vocabularyMap.get(vocName);
698
    }
699

    
700

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

    
704
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
705
        Map<String, String> retMap = new HashMap<String, String>();
706

    
707
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
708
        boolean foundData = false;
709
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
710
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
711
                return compatibilityClasses;
712
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
713
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
714
                    retMap.put(entry.getKey(), entry.getValue());
715
                    foundData = true;
716
                }
717
            } else {
718
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
719
                    retMap.put(entry.getKey(), entry.getValue());
720
            }
721
        }
722

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

    
727
        return retMap;
728
    }
729

    
730
    @Override
731
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
732

    
733
        LOGGER.debug("Getting datasource classes for mode: " + mode);
734

    
735
        Map<String, String> retMap = new HashMap<String, String>();
736

    
737
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
738
            if (mode.equalsIgnoreCase("aggregator")) {
739
                if (entry.getKey().contains("aggregator"))
740
                    retMap.put(entry.getKey(), entry.getValue());
741
            } else if (mode.equalsIgnoreCase("journal")) {
742
                if (entry.getKey().contains("journal"))
743
                    retMap.put(entry.getKey(), entry.getValue());
744
            } else if (mode.equalsIgnoreCase("opendoar")) {
745
                if (entry.getKey().contains("pubsrepository"))
746
                    retMap.put(entry.getKey(), entry.getValue());
747
            } else if (mode.equalsIgnoreCase("re3data")) {
748
                if (entry.getKey().contains("datarepository"))
749
                    retMap.put(entry.getKey(), entry.getValue());
750
            }
751
        }
752
        return retMap;
753

    
754
    }
755

    
756
    @Override
757
    public String getCountryName(String countryCode) {
758
        return inverseCountriesMap.get(countryCode);
759
    }
760

    
761
}
(8-8/10)