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
        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
        LOGGER.debug("Repository equals : " + Converter.repositoryObjectToJson(repository));
271
        restTemplate.postForObject(uriComponents.toUri(),Converter.repositoryObjectToJson(repository),String.class);
272
    }
273

    
274
    @Override
275
    public void deleteRepositoryInterface(@PathVariable("id") String id){
276
        UriComponents uriComponents = UriComponentsBuilder
277
                .fromHttpUrl(baseAddress + "/ds/api/")
278
                .path("/{id}/")
279
                .build().expand(id).encode();
280
        restTemplate.delete(uriComponents.toUri());
281
    }
282

    
283
    @Override
284
    public RepositoryInterface addRepositoryInterface(RepositoryInterface iFace) throws JSONException {
285

    
286
        UriComponents uriComponents = UriComponentsBuilder
287
                .fromHttpUrl(baseAddress + "/ds/api/add/")
288
                .build()
289
                .encode();
290
        String rs =  restTemplate.postForObject(uriComponents.toUri(), Converter.repositoryInterfaceObjectToJson(iFace),String.class);
291
        return Converter.jsonToRepositoryInterfaceObject(new JSONArray(rs).getJSONObject(0));
292
    }
293

    
294
    @Override
295
    public List<String> getDnetCountries() {
296
        LOGGER.debug("Getting dnet-countries!");
297
        return Converter.readFile("countries.txt");
298
    }
299

    
300
    @Override
301
    public List<String> getTypologies() {
302
        return Converter.readFile("typologies.txt");
303
    }
304

    
305
    @Override
306
    public List<Timezone> getTimezones() {
307
        List<String> timezones =  Converter.readFile("timezones.txt");
308
        return Converter.toTimezones(timezones);
309
    }
310

    
311
    @Override
312
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
313
                                      @RequestParam(value = "managed")  String managed) {
314

    
315
        UriComponents uriComponents = UriComponentsBuilder
316
                .fromHttpUrl(baseAddress + "/ds/manage/")
317
                .queryParam("id",id)
318
                .queryParam("managed",managed)
319
                .build().encode();
320

    
321
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
322
    }
323

    
324
    @Override
325
    public String updateEnglishName(@RequestParam(value = "id")   String id,
326
                                    @RequestParam(value = "englishname")  String englishName) {
327

    
328
        UriComponents uriComponents = UriComponentsBuilder
329
                .fromHttpUrl(baseAddress + "/ds/manage/")
330
                .queryParam("dsId",id)
331
                .queryParam("englishname",englishName)
332
                .build().encode();
333
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
334

    
335

    
336
    }
337

    
338
    @Override
339
    public String updateLatitude(@RequestParam(value = "id")   String id,
340
                                 @RequestParam(value = "managed")  String latitude) {
341

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

    
350
    @Override
351
    public String updateLongitude(@RequestParam(value = "id")   String id,
352
                                  @RequestParam(value = "longitude")  String longitude) {
353

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

    
362
    @Override
363
    public String updateOfficialName(@RequestParam(value = "id")   String id,
364
                                     @RequestParam(value = "officialname")  String officialname) {
365

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

    
374
    @Override
375
    public String updateTimezone(@RequestParam(value = "id")   String id,
376
                                 @RequestParam(value = "timezone")  String timezone) {
377
        UriComponents uriComponents = UriComponentsBuilder
378
                .fromHttpUrl(baseAddress + "/ds/update/timezone")
379
                .queryParam("dsId",id)
380
                .queryParam("timezone",timezone)
381
                .build().encode();
382
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
383
    }
384

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

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

    
407
    @Override
408
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String user_email,
409
                                           @PathVariable("page") String page,
410
                                           @PathVariable("size") String size) throws JSONException {
411
        UriComponents uriComponents = UriComponentsBuilder
412
                .fromHttpUrl(baseAddress + "/api/baseurl/")
413
                .path("/{page}/{size}")
414
                .queryParam("userEmail",user_email)
415
                .build().expand(page,size).encode();
416
        return Arrays.asList(restTemplate.getForObject(uriComponents.toUri(), String[].class));
417
    }
418

    
419
    @Override
420
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
421

    
422
        List<String> resultSet = new ArrayList<>();
423
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
424
            if (mode.equalsIgnoreCase("aggregator")) {
425
                if (entry.getKey().contains("aggregator"))
426
                    resultSet.add(entry.getValue());
427
            } else if (mode.equalsIgnoreCase("journal")) {
428
                if (entry.getKey().contains("journal"))
429
                    resultSet.add(entry.getValue());
430
            } else if (mode.equalsIgnoreCase("opendoar")) {
431
                if (entry.getKey().contains("pubsrepository"))
432
                    resultSet.add(entry.getValue());
433
            } else if (mode.equalsIgnoreCase("re3data")) {
434
                if (entry.getKey().contains("datarepository"))
435
                    resultSet.add(entry.getValue());
436
            }
437
        }
438

    
439

    
440
        return resultSet;
441
    }
442

    
443
    private Vocabulary getVocabulary(String vocName) {
444

    
445
        if (!vocabularyMap.containsKey(vocName)) {
446
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
447
        }
448
        return vocabularyMap.get(vocName);
449
    }
450

    
451

    
452
    @Override
453
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
454

    
455
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
456
        Map<String, String> retMap = new HashMap<String, String>();
457

    
458
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
459
        boolean foundData = false;
460
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
461
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
462
                return compatibilityClasses;
463
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
464
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
465
                    retMap.put(entry.getKey(), entry.getValue());
466
                    foundData = true;
467
                }
468
            } else {
469
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
470
                    retMap.put(entry.getKey(), entry.getValue());
471
            }
472
        }
473

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

    
478
        return retMap;
479
    }
480

    
481
    @Override
482
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
483

    
484
        LOGGER.debug("Getting datasource classes for mode: " + mode);
485

    
486
        Map<String, String> retMap = new HashMap<String, String>();
487

    
488
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
489
            if (mode.equalsIgnoreCase("aggregator")) {
490
                if (entry.getKey().contains("aggregator"))
491
                    retMap.put(entry.getKey(), entry.getValue());
492
            } else if (mode.equalsIgnoreCase("journal")) {
493
                if (entry.getKey().contains("journal"))
494
                    retMap.put(entry.getKey(), entry.getValue());
495
            } else if (mode.equalsIgnoreCase("opendoar")) {
496
                if (entry.getKey().contains("pubsrepository"))
497
                    retMap.put(entry.getKey(), entry.getValue());
498
            } else if (mode.equalsIgnoreCase("re3data")) {
499
                if (entry.getKey().contains("datarepository"))
500
                    retMap.put(entry.getKey(), entry.getValue());
501
            }
502
        }
503
        return retMap;
504

    
505
    }
506

    
507
    @Override
508
    public String getCountryName(String countryCode) {
509
        return inverseCountriesMap.get(countryCode);
510
    }
511

    
512
}
(8-8/10)