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 = 0;
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
        String filterKey = "UNKNOWN";
130
        if(mode.equalsIgnoreCase("opendoar")) {
131
            filterKey = "openaire____::opendoar";
132
        } else if(mode.equalsIgnoreCase("re3data")) {
133
            filterKey = "openaire____::re3data";
134
        } else if(mode.equalsIgnoreCase("jour_aggr")) {
135
            filterKey = "infrastruct_::openaire";
136
        }
137

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

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

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

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

    
167

    
168
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
169

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

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

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

    
197
    @Override
198
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException {
199

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

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

    
212
    @Override
213
    public Aggregations getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
214

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

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

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

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

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

    
248
    @Override
249
    public RepositoryInterface getRepositoyInterface(@PathVariable("id") String id) throws JSONException {
250

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

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

    
260
    @Override
261
    public void addRepository(@RequestBody Repository repository) throws JSONException {
262

    
263
        LOGGER.debug("Adding repository with name : " + repository.getOfficialName());
264

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

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

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

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

    
289
    @Override
290
    public RepositoryInterface addRepositoryInterface(RepositoryInterface iFace) throws JSONException {
291

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

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

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

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

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

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

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

    
334
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
335
    }
336

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

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

    
348

    
349
    }
350

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

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

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

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

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

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

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

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

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

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

    
432
    @Override
433
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
434

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

    
452

    
453
        return resultSet;
454
    }
455

    
456
    private Vocabulary getVocabulary(String vocName) {
457

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

    
464

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

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

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

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

    
491
        return retMap;
492
    }
493

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

    
497
        LOGGER.debug("Getting datasource classes for mode: " + mode);
498

    
499
        Map<String, String> retMap = new HashMap<String, String>();
500

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

    
518
    }
519

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

    
525
}
(8-8/10)