Project

General

Profile

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

    
3
import eu.dnetlib.domain.enabling.Vocabulary;
4
import eu.dnetlib.repo.manager.service.utils.Converter;
5
import eu.dnetlib.domain.data.Repository;
6
import eu.dnetlib.domain.data.RepositoryInterface;
7
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
8
import org.apache.log4j.Logger;
9
import org.json.JSONArray;
10
import org.json.JSONException;
11
import org.json.JSONObject;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.beans.factory.annotation.Value;
14
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
15
import org.springframework.stereotype.Component;
16
import org.springframework.web.bind.annotation.PathVariable;
17
import org.springframework.web.bind.annotation.RequestBody;
18
import org.springframework.web.bind.annotation.RequestParam;
19
import org.springframework.web.client.RestTemplate;
20
import org.springframework.web.util.UriComponents;
21
import org.springframework.web.util.UriComponentsBuilder;
22
import javax.annotation.PostConstruct;
23
import java.util.*;
24
import java.util.concurrent.ConcurrentHashMap;
25
import eu.dnetlib.repo.manager.shared.*;
26

    
27
@Component
28
public class RepositoryApiImpl implements RepositoryApi {
29

    
30
    @Value("${api.baseAddress}")
31
    private String baseAddress;
32

    
33
    private RestTemplate restTemplate = null;
34

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

    
37
    private static final Logger LOGGER = Logger.getLogger(RepositoryApiImpl.class);
38

    
39
    @Autowired
40
    private VocabularyLoader vocabularyLoader;
41

    
42
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
43

    
44
    private Map<String,String> countriesMap = new HashMap<>();
45
    private Map<String,String> inverseCountriesMap = new HashMap<>();
46

    
47

    
48
    @PostConstruct
49
    private void init(){
50
        LOGGER.debug("Initialization method of repository api!");
51

    
52
        restTemplate = new RestTemplate();
53
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
54

    
55
        for (String vocName : vocabularyNames) {
56
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
57
        }
58

    
59
        Country[] countries = getCountries();
60
        for(Country c: countries){
61
            countriesMap.put(c.getName(),c.getCode());
62
            inverseCountriesMap.put(c.getCode(),c.getName());
63
        }
64

    
65

    
66
    }
67

    
68
    @Override
69
    public Aggregations testAggregations() throws JSONException {
70

    
71
        int page = 1;
72
        int size = 1000;
73

    
74
        UriComponents uriComponents = UriComponentsBuilder
75
                .fromHttpUrl(baseAddress + "/ds/list/")
76
                .path("/{page}/{size}/")
77
                .build().expand(page,size).encode();
78

    
79
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
80
        while(!rs.equals("[]")){
81

    
82
            Aggregations aggregations = getFirstNonEmptyAggregation(rs);
83
            if(aggregations != null)
84
                return aggregations;
85

    
86
            LOGGER.debug("Checked " + page*size + " records!");
87

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

    
99
    private Aggregations getFirstNonEmptyAggregation(String rs) throws JSONException {
100

    
101
        JSONArray ids = new JSONArray(rs);
102
        for(int i=0;i<ids.length();i++){
103
            String id = ids.getString(i);
104
            Aggregations aggregations = getRepositoryAggregations(id);
105
            if(aggregations.getAggregationHistory() != null)
106
                return aggregations;
107
        }
108
        return null;
109
    }
110

    
111
    @Override
112
    public Country[] getCountries()  {
113
        UriComponents uriComponents = UriComponentsBuilder
114
                .fromHttpUrl(baseAddress + "/ds/countries")
115
                .build().encode();
116
        return restTemplate.getForObject(uriComponents.toUri(),Country[].class);
117
    }
118

    
119

    
120
    @Override
121
    public List<Repository> getRepositoriesByCountry(@PathVariable("country") String country,
122
                                                     @PathVariable("mode") String mode) throws JSONException {
123

    
124
        LOGGER.debug("Getting repositories by country!");
125
        int page = 0;
126
        int size = 100;
127

    
128
        String countryCode = countriesMap.get(country);
129
        countryCode = "GR";
130
        String filterKey = "UNKNOWN";
131
        if(mode.equalsIgnoreCase("opendoar")) {
132
            filterKey = "openaire____::opendoar";
133
        } else if(mode.equalsIgnoreCase("re3data")) {
134
            filterKey = "openaire____::re3data";
135
        } else if(mode.equalsIgnoreCase("jour_aggr")) {
136
            filterKey = "infrastruct_::openaire";
137
        }
138

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

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

    
152
            Collection<Repository> repos = this.getRepositoriesByMode(filterKey,rep);
153
            resultSet.addAll(repos);
154

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

    
169

    
170
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
171

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

    
180
    @Override
181
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
182
                                                  @PathVariable("page") String page,
183
                                                  @PathVariable("size") String size) throws JSONException {
184

    
185
        LOGGER.debug("Retreiving repositories of user : " + userEmail + " with params: " + baseAddress + "-" + page + "/" + size);
186
        UriComponents uriComponents = UriComponentsBuilder
187
                .fromHttpUrl(baseAddress + "/ds/search/email/")
188
                .path("/{page}/{size}/")
189
                .queryParam("contactemail",userEmail)
190
                .build().expand(page,size).encode();
191
        
192
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
193
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
194
        for(Repository r : repos)
195
            r.setCountryName(getCountryName(r.getCountryCode()));
196
        return repos;
197
    }
198

    
199
    @Override
200
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException {
201

    
202
        UriComponents uriComponents = UriComponentsBuilder
203
                .fromHttpUrl(baseAddress + "/ds/get/")
204
                .path("/{id}/")
205
                .build().expand(id).encode();
206

    
207
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
208
        Repository repo = Converter.jsonToRepositoryObject(new JSONObject(rs));
209
        if (repo != null)
210
            repo.setCountryName(getCountryName(repo.getCountryCode()));
211
        return repo;
212
    }
213

    
214
    @Override
215
    public Aggregations getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
216

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

    
222
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
223
        JSONObject repository = new JSONObject(rs);
224

    
225
        Aggregations aggregations = new Aggregations();
226
        
227
        aggregations.setAggregationHistory(Converter.getAggregationHistoryFromJson(repository));
228
        aggregations.setLastCollection(Converter.getLastCollectionFromJson(repository));
229
        aggregations.setLastTransformation(Converter.getLastTransformationFromJson(repository));
230
        return aggregations;
231
    }
232

    
233
    @Override
234
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
235
                                                  @PathVariable("page") String page,
236
                                                  @PathVariable("size") String size) throws JSONException {
237
        UriComponents uriComponents = UriComponentsBuilder
238
                .fromHttpUrl(baseAddress + "/ds/search/name/")
239
                .path("/{page}/{size}")
240
                .queryParam("name",name)
241
                .build().expand(page,size).encode();
242

    
243
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
244
        List<Repository> repos = Converter.jsonToRepositoryList(new JSONArray(rs));
245
        for(Repository r : repos)
246
            r.setCountryName(getCountryName(r.getCountryCode()));
247
        return repos;
248
    }
249

    
250
    @Override
251
    public RepositoryInterface getRepositoyInterface(@PathVariable("id") String id) throws JSONException {
252

    
253
        UriComponents uriComponents = UriComponentsBuilder
254
                .fromHttpUrl(baseAddress + "/ds/api/")
255
                .path("/{id}/")
256
                .build().expand(id).encode();
257

    
258
        String rs = restTemplate.getForObject(uriComponents.toUri(),String.class);
259
        return  Converter.jsonToRepositoryInterfaceObject(new JSONArray(rs).getJSONObject(0));
260
    }
261

    
262
    @Override
263
    public void addRepository(@RequestBody Repository repository) throws JSONException {
264

    
265
        LOGGER.debug("Adding repository with name : " + repository.getOfficialName());
266

    
267
        UriComponents uriComponents = UriComponentsBuilder
268
                .fromHttpUrl(baseAddress + "/ds/add/")
269
                .build()
270
                .encode();
271

    
272
        try {
273
            LOGGER.debug("Repository equals : " + Converter.repositoryObjectToJson(repository));
274
        }catch (Exception e){
275
            LOGGER.debug("JSON exception ", e);
276
            throw e;
277
        }
278

    
279
        restTemplate.postForObject(uriComponents.toUri(),Converter.repositoryObjectToJson(repository),String.class);
280
    }
281

    
282
    @Override
283
    public void deleteRepositoryInterface(@PathVariable("id") String id){
284
        UriComponents uriComponents = UriComponentsBuilder
285
                .fromHttpUrl(baseAddress + "/ds/api/")
286
                .path("/{id}/")
287
                .build().expand(id).encode();
288
        restTemplate.delete(uriComponents.toUri());
289
    }
290

    
291
    @Override
292
    public RepositoryInterface addRepositoryInterface(RepositoryInterface iFace) throws JSONException {
293

    
294
        try {
295
            LOGGER.debug("Repository iface equals : " + Converter.repositoryInterfaceObjectToJson(iFace));
296
        }catch (Exception e){
297
            LOGGER.debug("JSON exception ", e);
298
            throw e;
299
        }
300

    
301
        UriComponents uriComponents = UriComponentsBuilder
302
                .fromHttpUrl(baseAddress + "/ds/api/add/")
303
                .build()
304
                .encode();
305
        String rs =  restTemplate.postForObject(uriComponents.toUri(), Converter.repositoryInterfaceObjectToJson(iFace),String.class);
306
        return Converter.jsonToRepositoryInterfaceObject(new JSONArray(rs).getJSONObject(0));
307
    }
308

    
309
    @Override
310
    public List<String> getDnetCountries() {
311
        LOGGER.debug("Getting dnet-countries!");
312
        return Converter.readFile("countries.txt");
313
    }
314

    
315
    @Override
316
    public List<String> getTypologies() {
317
        return Converter.readFile("typologies.txt");
318
    }
319

    
320
    @Override
321
    public List<Timezone> getTimezones() {
322
        List<String> timezones =  Converter.readFile("timezones.txt");
323
        return Converter.toTimezones(timezones);
324
    }
325

    
326
    @Override
327
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
328
                                      @RequestParam(value = "managed")  String managed) {
329

    
330
        UriComponents uriComponents = UriComponentsBuilder
331
                .fromHttpUrl(baseAddress + "/ds/manage/")
332
                .queryParam("id",id)
333
                .queryParam("managed",managed)
334
                .build().encode();
335

    
336
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
337
    }
338

    
339
    @Override
340
    public String updateEnglishName(@RequestParam(value = "id")   String id,
341
                                    @RequestParam(value = "englishname")  String englishName) {
342

    
343
        UriComponents uriComponents = UriComponentsBuilder
344
                .fromHttpUrl(baseAddress + "/ds/manage/")
345
                .queryParam("dsId",id)
346
                .queryParam("englishname",englishName)
347
                .build().encode();
348
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
349

    
350

    
351
    }
352

    
353
    @Override
354
    public String updateLatitude(@RequestParam(value = "id")   String id,
355
                                 @RequestParam(value = "managed")  String latitude) {
356

    
357
        UriComponents uriComponents = UriComponentsBuilder
358
                .fromHttpUrl(baseAddress + "/ds/manage/")
359
                .queryParam("dsId",id)
360
                .queryParam("latitude",latitude)
361
                .build().encode();
362
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
363
    }
364

    
365
    @Override
366
    public String updateLongitude(@RequestParam(value = "id")   String id,
367
                                  @RequestParam(value = "longitude")  String longitude) {
368

    
369
        UriComponents uriComponents = UriComponentsBuilder
370
                .fromHttpUrl(baseAddress + "/ds/manage/")
371
                .queryParam("dsId",id)
372
                .queryParam("longitude",longitude)
373
                .build().encode();
374
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
375
    }
376

    
377
    @Override
378
    public String updateOfficialName(@RequestParam(value = "id")   String id,
379
                                     @RequestParam(value = "officialname")  String officialname) {
380

    
381
        UriComponents uriComponents = UriComponentsBuilder
382
                .fromHttpUrl(baseAddress + "/ds/manage/")
383
                .queryParam("dsId",id)
384
                .queryParam("officialname",officialname)
385
                .build().encode();
386
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
387
    }
388

    
389
    @Override
390
    public String updateTimezone(@RequestParam(value = "id")   String id,
391
                                 @RequestParam(value = "timezone")  String timezone) {
392
        UriComponents uriComponents = UriComponentsBuilder
393
                .fromHttpUrl(baseAddress + "/ds/update/timezone")
394
                .queryParam("dsId",id)
395
                .queryParam("timezone",timezone)
396
                .build().encode();
397
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
398
    }
399

    
400
    @Override
401
    public String updateTypology(@RequestParam(value = "id")   String id,
402
                                 @RequestParam(value = "typology")  String typology) {
403
        UriComponents uriComponents = UriComponentsBuilder
404
                .fromHttpUrl(baseAddress + "/ds/update/typology")
405
                .queryParam("dsId",id)
406
                .queryParam("typology",typology)
407
                .build().encode();
408
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
409
    }
410

    
411
    @Override
412
    public String updateLogoUrl(@RequestParam(value = "id")   String id,
413
                                @RequestParam(value = "logoUrl") String logoUrl) {
414
        UriComponents uriComponents = UriComponentsBuilder
415
                .fromHttpUrl(baseAddress + "/ds/update/logourl")
416
                .queryParam("dsId",id)
417
                .queryParam("logourl",logoUrl)
418
                .build().encode();
419
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
420
    }
421

    
422
    @Override
423
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String user_email,
424
                                           @PathVariable("page") String page,
425
                                           @PathVariable("size") String size) throws JSONException {
426
        UriComponents uriComponents = UriComponentsBuilder
427
                .fromHttpUrl(baseAddress + "/api/baseurl/")
428
                .path("/{page}/{size}")
429
                .queryParam("userEmail",user_email)
430
                .build().expand(page,size).encode();
431
        return Arrays.asList(restTemplate.getForObject(uriComponents.toUri(), String[].class));
432
    }
433

    
434
    @Override
435
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
436

    
437
        List<String> resultSet = new ArrayList<>();
438
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
439
            if (mode.equalsIgnoreCase("aggregator")) {
440
                if (entry.getKey().contains("aggregator"))
441
                    resultSet.add(entry.getValue());
442
            } else if (mode.equalsIgnoreCase("journal")) {
443
                if (entry.getKey().contains("journal"))
444
                    resultSet.add(entry.getValue());
445
            } else if (mode.equalsIgnoreCase("opendoar")) {
446
                if (entry.getKey().contains("pubsrepository"))
447
                    resultSet.add(entry.getValue());
448
            } else if (mode.equalsIgnoreCase("re3data")) {
449
                if (entry.getKey().contains("datarepository"))
450
                    resultSet.add(entry.getValue());
451
            }
452
        }
453

    
454

    
455
        return resultSet;
456
    }
457

    
458
    private Vocabulary getVocabulary(String vocName) {
459

    
460
        if (!vocabularyMap.containsKey(vocName)) {
461
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
462
        }
463
        return vocabularyMap.get(vocName);
464
    }
465

    
466

    
467
    @Override
468
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
469

    
470
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
471
        Map<String, String> retMap = new HashMap<String, String>();
472

    
473
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
474
        boolean foundData = false;
475
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
476
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
477
                return compatibilityClasses;
478
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
479
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
480
                    retMap.put(entry.getKey(), entry.getValue());
481
                    foundData = true;
482
                }
483
            } else {
484
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
485
                    retMap.put(entry.getKey(), entry.getValue());
486
            }
487
        }
488

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

    
493
        return retMap;
494
    }
495

    
496
    @Override
497
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
498

    
499
        LOGGER.debug("Getting datasource classes for mode: " + mode);
500

    
501
        Map<String, String> retMap = new HashMap<String, String>();
502

    
503
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
504
            if (mode.equalsIgnoreCase("aggregator")) {
505
                if (entry.getKey().contains("aggregator"))
506
                    retMap.put(entry.getKey(), entry.getValue());
507
            } else if (mode.equalsIgnoreCase("journal")) {
508
                if (entry.getKey().contains("journal"))
509
                    retMap.put(entry.getKey(), entry.getValue());
510
            } else if (mode.equalsIgnoreCase("opendoar")) {
511
                if (entry.getKey().contains("pubsrepository"))
512
                    retMap.put(entry.getKey(), entry.getValue());
513
            } else if (mode.equalsIgnoreCase("re3data")) {
514
                if (entry.getKey().contains("datarepository"))
515
                    retMap.put(entry.getKey(), entry.getValue());
516
            }
517
        }
518
        return retMap;
519

    
520
    }
521

    
522
    @Override
523
    public String getCountryName(String countryCode) {
524
        return inverseCountriesMap.get(countryCode);
525
    }
526

    
527
}
(8-8/10)