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

    
45
    @PostConstruct
46
    private void init(){
47
        LOGGER.debug("Initialization method of repository api!");
48

    
49
        restTemplate = new RestTemplate();
50
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
51

    
52
        for (String vocName : vocabularyNames) {
53
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
54
        }
55

    
56
    }
57

    
58
    @Override
59
    public Aggregations testAggregations() throws JSONException {
60

    
61
        int page = 1;
62
        int size = 1000;
63

    
64
        UriComponents uriComponents = UriComponentsBuilder
65
                .fromHttpUrl(baseAddress + "/ds/list/")
66
                .path("/{page}/{size}/")
67
                .build().expand(page,size).encode();
68

    
69
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
70
        while(!rs.equals("[]")){
71

    
72
            Aggregations aggregations = getFirstNonEmptyAggregation(rs);
73
            if(aggregations != null)
74
                return aggregations;
75

    
76
            LOGGER.debug("Checked " + page*size + " records!");
77

    
78
            page+=1;
79
            uriComponents = UriComponentsBuilder
80
                    .fromHttpUrl(baseAddress + "/ds/list/")
81
                    .path("/{page}/{size}/")
82
                    .build().expand(page,size).encode();
83
            rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
84
        }
85
        
86
        return null;
87
    }
88

    
89
    private Aggregations getFirstNonEmptyAggregation(String rs) throws JSONException {
90

    
91
        JSONArray ids = new JSONArray(rs);
92
        for(int i=0;i<ids.length();i++){
93
            String id = ids.getString(i);
94
            Aggregations aggregations = getRepositoryAggregations(id);
95
            if(aggregations.getAggregationHistory() != null)
96
                return aggregations;
97
        }
98
        return null;
99
    }
100

    
101
    @Override
102
    public Country[] getCountries()  {
103
        UriComponents uriComponents = UriComponentsBuilder
104
                .fromHttpUrl(baseAddress + "/ds/countries")
105
                .build().encode();
106
        return restTemplate.getForObject(uriComponents.toUri(),Country[].class);
107
    }
108

    
109

    
110
    @Override
111
    public List<Repository> getRepositoriesByCountry(@PathVariable("country") String country,
112
                                                     @PathVariable("country") String mode) throws JSONException {
113

    
114
        LOGGER.debug("Getting repositories by country!");
115
        int page = 1;
116
        int size = 10;
117
        String countryCode = getCountryCode(country);
118

    
119

    
120
        LOGGER.debug("Country code equals : " + countryCode);
121
        UriComponents uriComponents = UriComponentsBuilder
122
                                            .fromHttpUrl(baseAddress + "/ds/search/country/")
123
                                            .path("/{page}/{size}/")
124
                                            .queryParam("country",country)
125
                                            .build().expand(page,size).encode();
126

    
127
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
128
        List<Repository> resultSet = new ArrayList<>();
129
        while(!rs.equals("[]")){
130
            List<Repository> rep = Converter.jsonToRepositoryList(new JSONArray(rs));
131

    
132
            Collection<Repository> repos = this.getRepositoriesByMode(mode,rep);
133
            //this.addRepos(repIDs,repos);
134
            resultSet.addAll(repos);
135

    
136
            page+=1;
137
            uriComponents = UriComponentsBuilder
138
                    .fromHttpUrl(baseAddress + "/ds/search/country/")
139
                    .path("/{page}/{size}/")
140
                    .queryParam("country",countryCode)
141
                    .build().expand(page,size).encode();
142
            rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
143
        }
144
        return resultSet;
145
    }
146

    
147
    private String getCountryCode(String country) {
148

    
149
        Country[] countries = getCountries();
150
        for(Country c : countries)
151
            if(c.getName().equals(country))
152
                return c.getCode();
153
        return country;
154
    }
155

    
156
    private void addRepos(Set<String> resultSet, Collection<String> repos) {
157
        for(String s : repos)
158
            if(!resultSet.contains(s))
159
                resultSet.add(s);
160
    }
161

    
162
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
163

    
164
        List<Repository> reps = new ArrayList<>();
165

    
166
        for(Repository r : rs)
167
            if(r.getCollectedFrom().equals(mode))
168
                reps.add(r);
169

    
170
        return reps;
171
    }
172

    
173
    @Override
174
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
175
                                                  @PathVariable("page") String page,
176
                                                  @PathVariable("size") String size) throws JSONException {
177

    
178
        LOGGER.debug("Retreiving repositories of user : " + userEmail + " with params: " + baseAddress + "-" + page + "/" + size);
179
        UriComponents uriComponents = UriComponentsBuilder
180
                .fromHttpUrl(baseAddress + "/ds/search/email/")
181
                .path("/{page}/{size}/")
182
                .queryParam("contactemail",userEmail)
183
                .build().expand(page,size).encode();
184
        
185
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
186
        return Converter.jsonToRepositoryList(new JSONArray(rs));
187
    }
188

    
189
    @Override
190
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException {
191

    
192
        UriComponents uriComponents = UriComponentsBuilder
193
                .fromHttpUrl(baseAddress + "/ds/get/")
194
                .path("/{id}/")
195
                .build().expand(id).encode();
196

    
197
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
198
        return  Converter.jsonToRepositoryObject(new JSONObject(rs));
199
    }
200

    
201
    @Override
202
    public Aggregations getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
203

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

    
209
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
210
        JSONObject repository = new JSONObject(rs);
211

    
212
        Aggregations aggregations = new Aggregations();
213
        
214
        aggregations.setAggregationHistory(Converter.getAggregationHistoryFromJson(repository));
215
        aggregations.setLastCollection(Converter.getLastCollectionFromJson(repository));
216
        aggregations.setLastTransformation(Converter.getLastTransformationFromJson(repository));
217
        return aggregations;
218
    }
219

    
220
    @Override
221
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
222
                                                  @PathVariable("page") String page,
223
                                                  @PathVariable("size") String size) throws JSONException {
224
        UriComponents uriComponents = UriComponentsBuilder
225
                .fromHttpUrl(baseAddress + "/ds/search/name/")
226
                .path("/{page}/{size}")
227
                .queryParam("name",name)
228
                .build().expand(page,size).encode();
229

    
230
        String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
231
        return Converter.jsonToRepositoryList(new JSONArray(rs));
232
    }
233

    
234
    @Override
235
    public RepositoryInterface getRepositoyInterface(@PathVariable("id") String id) throws JSONException {
236

    
237
        UriComponents uriComponents = UriComponentsBuilder
238
                .fromHttpUrl(baseAddress + "/ds/service/")
239
                .path("/{id}/")
240
                .build().expand(id).encode();
241

    
242
        String rs = restTemplate.getForObject(uriComponents.toUri(),String.class);
243
        return  Converter.jsonToRepositoryInterfaceObject(new JSONArray(rs).getJSONObject(0));
244
    }
245

    
246
    @Override
247
    public String addRepository(@RequestBody Repository repository) throws JSONException {
248
        UriComponents uriComponents = UriComponentsBuilder
249
                .fromHttpUrl(baseAddress + "/ds/add/")
250
                .build()
251
                .encode();
252
        return restTemplate.postForObject(uriComponents.toUri(),Converter.repositoryObjectToJson(repository),String.class);
253
    }
254

    
255
    @Override
256
    public String addRepositoryInterface(RepositoryInterface repositoryInterface) throws JSONException {
257
        UriComponents uriComponents = UriComponentsBuilder
258
                .fromHttpUrl(baseAddress + "/ds/service/add/")
259
                .build()
260
                .encode();
261
        return restTemplate.postForObject(uriComponents.toUri(), Converter.repositoryInterfaceObjectToJson(repositoryInterface),String.class);
262
    }
263

    
264
    @Override
265
    public List<String> getDnetCountries() {
266
        LOGGER.debug("Getting dnet-countries!");
267
        return Converter.readFile("countries.txt");
268
    }
269

    
270
    @Override
271
    public List<String> getTypologies() {
272
        return Converter.readFile("typologies.txt");
273
    }
274

    
275
    @Override
276
    public List<Timezone> getTimezones() {
277
        List<String> timezones =  Converter.readFile("timezones.txt");
278
        return Converter.toTimezones(timezones);
279
    }
280

    
281
    @Override
282
    public String updateManagedStatus(@RequestParam(value = "id")   String id,
283
                                      @RequestParam(value = "managed")  String managed) {
284

    
285
        UriComponents uriComponents = UriComponentsBuilder
286
                .fromHttpUrl(baseAddress + "/ds/manage/")
287
                .queryParam("id",id)
288
                .queryParam("managed",managed)
289
                .build().encode();
290

    
291
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
292
    }
293

    
294
    @Override
295
    public String updateEnglishName(@RequestParam(value = "id")   String id,
296
                                    @RequestParam(value = "englishname")  String englishName) {
297

    
298
        UriComponents uriComponents = UriComponentsBuilder
299
                .fromHttpUrl(baseAddress + "/ds/manage/")
300
                .queryParam("dsId",id)
301
                .queryParam("englishname",englishName)
302
                .build().encode();
303
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
304

    
305

    
306
    }
307

    
308
    @Override
309
    public String updateLatitude(@RequestParam(value = "id")   String id,
310
                                 @RequestParam(value = "managed")  String latitude) {
311

    
312
        UriComponents uriComponents = UriComponentsBuilder
313
                .fromHttpUrl(baseAddress + "/ds/manage/")
314
                .queryParam("dsId",id)
315
                .queryParam("latitude",latitude)
316
                .build().encode();
317
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
318
    }
319

    
320
    @Override
321
    public String updateLongitude(@RequestParam(value = "id")   String id,
322
                                  @RequestParam(value = "longitude")  String longitude) {
323

    
324
        UriComponents uriComponents = UriComponentsBuilder
325
                .fromHttpUrl(baseAddress + "/ds/manage/")
326
                .queryParam("dsId",id)
327
                .queryParam("longitude",longitude)
328
                .build().encode();
329
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
330
    }
331

    
332
    @Override
333
    public String updateOfficialName(@RequestParam(value = "id")   String id,
334
                                     @RequestParam(value = "officialname")  String officialname) {
335

    
336
        UriComponents uriComponents = UriComponentsBuilder
337
                .fromHttpUrl(baseAddress + "/ds/manage/")
338
                .queryParam("dsId",id)
339
                .queryParam("officialname",officialname)
340
                .build().encode();
341
        return restTemplate.postForObject(uriComponents.toUri(), null,String.class);
342
    }
343

    
344
    @Override
345
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String user_email,
346
                                           @PathVariable("page") String page,
347
                                           @PathVariable("size") String size) throws JSONException {
348
        UriComponents uriComponents = UriComponentsBuilder
349
                .fromHttpUrl(baseAddress + "/api/baseurl/")
350
                .path("/{page}/{size}")
351
                .queryParam("userEmail",user_email)
352
                .build().expand(page,size).encode();
353
        return Arrays.asList(restTemplate.getForObject(uriComponents.toUri(), String[].class));
354
    }
355

    
356
    @Override
357
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
358

    
359
        List<String> resultSet = new ArrayList<>();
360
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
361
            if (mode.equalsIgnoreCase("aggregator")) {
362
                if (entry.getKey().contains("aggregator"))
363
                    resultSet.add(entry.getValue());
364
            } else if (mode.equalsIgnoreCase("journal")) {
365
                if (entry.getKey().contains("journal"))
366
                    resultSet.add(entry.getValue());
367
            } else if (mode.equalsIgnoreCase("opendoar")) {
368
                if (entry.getKey().contains("pubsrepository"))
369
                    resultSet.add(entry.getValue());
370
            } else if (mode.equalsIgnoreCase("re3data")) {
371
                if (entry.getKey().contains("datarepository"))
372
                    resultSet.add(entry.getValue());
373
            }
374
        }
375

    
376

    
377
        return resultSet;
378
    }
379

    
380
    private Vocabulary getVocabulary(String vocName) {
381

    
382
        if (!vocabularyMap.containsKey(vocName)) {
383
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
384
        }
385
        return vocabularyMap.get(vocName);
386
    }
387

    
388

    
389
    @Override
390
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
391

    
392
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
393
        Map<String, String> retMap = new HashMap<String, String>();
394

    
395
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
396
        boolean foundData = false;
397
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
398
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
399
                return compatibilityClasses;
400
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
401
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
402
                    retMap.put(entry.getKey(), entry.getValue());
403
                    foundData = true;
404
                }
405
            } else {
406
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
407
                    retMap.put(entry.getKey(), entry.getValue());
408
            }
409
        }
410

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

    
415
        return retMap;
416
    }
417

    
418
    @Override
419
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
420

    
421
        LOGGER.debug("Getting datasource classes for mode: " + mode);
422

    
423
        Map<String, String> retMap = new HashMap<String, String>();
424

    
425
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
426
            if (mode.equalsIgnoreCase("aggregator")) {
427
                if (entry.getKey().contains("aggregator"))
428
                    retMap.put(entry.getKey(), entry.getValue());
429
            } else if (mode.equalsIgnoreCase("journal")) {
430
                if (entry.getKey().contains("journal"))
431
                    retMap.put(entry.getKey(), entry.getValue());
432
            } else if (mode.equalsIgnoreCase("opendoar")) {
433
                if (entry.getKey().contains("pubsrepository"))
434
                    retMap.put(entry.getKey(), entry.getValue());
435
            } else if (mode.equalsIgnoreCase("re3data")) {
436
                if (entry.getKey().contains("datarepository"))
437
                    retMap.put(entry.getKey(), entry.getValue());
438
            }
439
        }
440
        return retMap;
441

    
442
    }
443

    
444
}
(6-6/8)