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 List<String> 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
        List<String> ids = new ArrayList<>();
81
        while(!rs.equals("[]")){
82
            
83
            ids.addAll(getIdsWithNonEmptyAggregations(rs));
84

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

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

    
98
    private List<String> getIdsWithNonEmptyAggregations(String rs) throws JSONException {
99

    
100
        JSONArray ids = new JSONArray(rs);
101
        List<String> agg_ids = new ArrayList<>();
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
                agg_ids.add(id);
107
        }
108
        return agg_ids;
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
        try{
226
            aggregations.setAggregationHistory(Converter.getAggregationHistoryFromJson(repository));
227
            aggregations.setLastCollection(Converter.getLastCollectionFromJson(repository));
228
            aggregations.setLastTransformation(Converter.getLastTransformationFromJson(repository));
229
            return aggregations;
230
        }catch (JSONException e){
231
            LOGGER.debug("JSON aggregation exception " ,e);
232
            throw e;
233
        }
234

    
235
    }
236

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

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

    
254
    @Override
255
    public RepositoryInterface getRepositoyInterface(@PathVariable("id") String id) throws JSONException {
256

    
257
        UriComponents uriComponents = UriComponentsBuilder
258
                .fromHttpUrl(baseAddress + "/ds/api/")
259
                .path("/{id}/")
260
                .build().expand(id).encode();
261

    
262
        String rs = restTemplate.getForObject(uriComponents.toUri(),String.class);
263
        return  Converter.jsonToRepositoryInterfaceObject(new JSONArray(rs).getJSONObject(0));
264
    }
265

    
266
    @Override
267
    public void addRepository(@RequestBody Repository repository) throws JSONException {
268

    
269
        LOGGER.debug("Adding repository with name : " + repository.getOfficialName());
270

    
271
        UriComponents uriComponents = UriComponentsBuilder
272
                .fromHttpUrl(baseAddress + "/ds/add/")
273
                .build()
274
                .encode();
275

    
276
        try {
277
            LOGGER.debug("Repository equals : " + Converter.repositoryObjectToJson(repository));
278
        }catch (Exception e){
279
            LOGGER.debug("JSON exception ", e);
280
            throw e;
281
        }
282

    
283
        restTemplate.postForObject(uriComponents.toUri(),Converter.repositoryObjectToJson(repository),String.class);
284
    }
285

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

    
295
    @Override
296
    public RepositoryInterface addRepositoryInterface(RepositoryInterface iFace) throws JSONException {
297

    
298
        try {
299
            LOGGER.debug("Repository iface equals : " + Converter.repositoryInterfaceObjectToJson(iFace));
300
        }catch (Exception e){
301
            LOGGER.debug("JSON exception ", e);
302
            throw e;
303
        }
304

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

    
313
    @Override
314
    public List<String> getDnetCountries() {
315
        LOGGER.debug("Getting dnet-countries!");
316
        return Converter.readFile("countries.txt");
317
    }
318

    
319
    @Override
320
    public List<String> getTypologies() {
321
        return Converter.readFile("typologies.txt");
322
    }
323

    
324
    @Override
325
    public List<Timezone> getTimezones() {
326
        List<String> timezones =  Converter.readFile("timezones.txt");
327
        return Converter.toTimezones(timezones);
328
    }
329

    
330
    @Override
331
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
332
                                      @RequestParam(value = "managed")  String managed) {
333

    
334
        UriComponents uriComponents = UriComponentsBuilder
335
                .fromHttpUrl(baseAddress + "/ds/manage/")
336
                .queryParam("id",id)
337
                .queryParam("managed",managed)
338
                .build().encode();
339

    
340
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
341
    }
342

    
343
    @Override
344
    public String updateEnglishName(@RequestParam(value = "id")   String id,
345
                                    @RequestParam(value = "englishname")  String englishName) {
346

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

    
354

    
355
    }
356

    
357
    @Override
358
    public String updateLatitude(@RequestParam(value = "id")   String id,
359
                                 @RequestParam(value = "managed")  String latitude) {
360

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

    
369
    @Override
370
    public String updateLongitude(@RequestParam(value = "id")   String id,
371
                                  @RequestParam(value = "longitude")  String longitude) {
372

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

    
381
    @Override
382
    public String updateOfficialName(@RequestParam(value = "id")   String id,
383
                                     @RequestParam(value = "officialname")  String officialname) {
384

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

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

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

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

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

    
438
    @Override
439
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
440

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

    
458

    
459
        return resultSet;
460
    }
461

    
462
    private Vocabulary getVocabulary(String vocName) {
463

    
464
        if (!vocabularyMap.containsKey(vocName)) {
465
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
466
        }
467
        return vocabularyMap.get(vocName);
468
    }
469

    
470

    
471
    @Override
472
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
473

    
474
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
475
        Map<String, String> retMap = new HashMap<String, String>();
476

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

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

    
497
        return retMap;
498
    }
499

    
500
    @Override
501
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
502

    
503
        LOGGER.debug("Getting datasource classes for mode: " + mode);
504

    
505
        Map<String, String> retMap = new HashMap<String, String>();
506

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

    
524
    }
525

    
526
    @Override
527
    public String getCountryName(String countryCode) {
528
        return inverseCountriesMap.get(countryCode);
529
    }
530

    
531
}
(8-8/10)