Project

General

Profile

1 49362 panagiotis
package eu.dnetlib.repo.manager.service.controllers;
2 49236 panagiotis
3 51549 panagiotis
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import com.fasterxml.jackson.databind.SerializationFeature;
6 50051 panagiotis
import eu.dnetlib.domain.data.Repository;
7
import eu.dnetlib.domain.data.RepositoryInterface;
8 49450 panagiotis
import eu.dnetlib.domain.enabling.Vocabulary;
9 52781 panagiotis
import eu.dnetlib.repo.manager.service.domain.RequestFilter;
10
import eu.dnetlib.repo.manager.service.exception.ResourceNotFoundException;
11 49236 panagiotis
import eu.dnetlib.repo.manager.service.utils.Converter;
12 50570 panagiotis
import eu.dnetlib.repo.manager.shared.*;
13 49450 panagiotis
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
14 50570 panagiotis
import org.apache.commons.codec.digest.DigestUtils;
15 49763 panagiotis
import org.apache.log4j.Logger;
16 49236 panagiotis
import org.json.JSONArray;
17 49362 panagiotis
import org.json.JSONException;
18 49236 panagiotis
import org.json.JSONObject;
19 49450 panagiotis
import org.springframework.beans.factory.annotation.Autowired;
20 49236 panagiotis
import org.springframework.beans.factory.annotation.Value;
21 50570 panagiotis
import org.springframework.core.ParameterizedTypeReference;
22 52781 panagiotis
import org.springframework.http.HttpEntity;
23
import org.springframework.http.HttpHeaders;
24
import org.springframework.http.HttpMethod;
25
import org.springframework.http.ResponseEntity;
26 49245 panagiotis
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
27 52781 panagiotis
import org.springframework.security.access.annotation.Secured;
28
import org.springframework.security.access.prepost.PostAuthorize;
29 51656 panagiotis
import org.springframework.security.access.prepost.PreAuthorize;
30 49236 panagiotis
import org.springframework.stereotype.Component;
31
import org.springframework.web.bind.annotation.PathVariable;
32
import org.springframework.web.bind.annotation.RequestBody;
33
import org.springframework.web.bind.annotation.RequestParam;
34 50570 panagiotis
import org.springframework.web.client.RestClientException;
35 49245 panagiotis
import org.springframework.web.client.RestTemplate;
36 49304 panagiotis
import org.springframework.web.util.UriComponents;
37 49245 panagiotis
import org.springframework.web.util.UriComponentsBuilder;
38 50051 panagiotis
39 49304 panagiotis
import javax.annotation.PostConstruct;
40 49960 panagiotis
import java.sql.Timestamp;
41 49450 panagiotis
import java.util.*;
42
import java.util.concurrent.ConcurrentHashMap;
43 52781 panagiotis
import java.util.function.Function;
44
import java.util.stream.Collectors;
45 49236 panagiotis
46
@Component
47
public class RepositoryApiImpl implements RepositoryApi {
48
49 49304 panagiotis
    @Value("${api.baseAddress}")
50 49236 panagiotis
    private String baseAddress;
51
52 49304 panagiotis
    private RestTemplate restTemplate = null;
53
54 50051 panagiotis
    private HttpHeaders httpHeaders;
55
56 49450 panagiotis
    private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
57
58 49763 panagiotis
    private static final Logger LOGGER = Logger.getLogger(RepositoryApiImpl.class);
59
60 50570 panagiotis
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
61
    private String usageStatisticsDiagramsBaseURL;
62
63
    @Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
64
    private String usageStatisticsNumbersBaseURL;
65
66 49450 panagiotis
    @Autowired
67
    private VocabularyLoader vocabularyLoader;
68
69 50219 panagiotis
    @Autowired
70
    private PiWikApi piWikApi;
71
72 51831 panagiotis
    @Autowired
73
    private EmailUtils emailUtils;
74
75 49450 panagiotis
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
76
77 49960 panagiotis
    private Map<String, String> countriesMap = new HashMap<>();
78
    private Map<String, String> inverseCountriesMap = new HashMap<>();
79 49450 panagiotis
80 51549 panagiotis
    private static Map<String,List<String>> dataSourceClass = new HashMap<String,List<String>>(){{
81
        put("opendoar",new ArrayList<String>(){{ add("pubsrepository::institutional");
82
                                                    add("pubsrepository::thematic");
83
                                                    add("pubsrepository::unknown");
84
                                                    add("pubsrepository::mock");
85
        }});
86
        put("re3data",new ArrayList<String>(){{ add("datarepository::unknown");
87
        }});
88
        put("journal",new ArrayList<String>(){{ add("pubsrepository::journal");
89
        }});
90
        put("aggregator",new ArrayList<String>(){{ add("aggregator::pubsrepository::institutional");
91
                                                        add("aggregator::pubsrepository::journals");
92
                                                        add("aggregator::datarepository");
93
                                                        add("aggregator::pubsrepository::unknown");
94
        }});
95
    }};
96 49898 panagiotis
97 51549 panagiotis
    private static Map<String,String> invertedDataSourceClass = new HashMap<String,String>(){{
98
        put("pubsrepository::institutional","opendoar");
99
        put("pubsrepository::thematic","opendoar");
100
        put("pubsrepository::unknown","opendoar");
101
        put("pubsrepository::mock","opendoar");
102
103
        put("datarepository::unknown","re3data");
104
105
        put("pubsrepository::journal","journal");
106
107
        put("aggregator::pubsrepository::institutional","aggregator");
108
        put("aggregator::pubsrepository::journals","aggregator");
109
        put("aggregator::datarepository","aggregator");
110
        put("aggregator::pubsrepository::unknown","aggregator");
111
112
    }};
113
114
115
116 49304 panagiotis
    @PostConstruct
117 49960 panagiotis
    private void init() {
118 49770 panagiotis
        LOGGER.debug("Initialization method of repository api!");
119
120 49304 panagiotis
        restTemplate = new RestTemplate();
121
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
122 49450 panagiotis
123 50051 panagiotis
        httpHeaders = new HttpHeaders();
124
        httpHeaders.set("Content-Type", "application/json");
125
126 49450 panagiotis
        for (String vocName : vocabularyNames) {
127
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
128
        }
129
130 49898 panagiotis
        Country[] countries = getCountries();
131 49960 panagiotis
        for (Country c : countries) {
132
            countriesMap.put(c.getName(), c.getCode());
133
            inverseCountriesMap.put(c.getCode(), c.getName());
134 49898 panagiotis
        }
135
136
137 49304 panagiotis
    }
138
139 49236 panagiotis
    @Override
140 49960 panagiotis
    public Country[] getCountries() {
141 49304 panagiotis
        UriComponents uriComponents = UriComponentsBuilder
142
                .fromHttpUrl(baseAddress + "/ds/countries")
143
                .build().encode();
144 49960 panagiotis
        return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
145 49236 panagiotis
    }
146
147
148
    @Override
149 49790 panagiotis
    public List<Repository> getRepositoriesByCountry(@PathVariable("country") String country,
150 50219 panagiotis
                                                     @PathVariable("mode") String mode,
151
                                                     @RequestParam(value = "managed",required=false) Boolean managed) throws JSONException {
152 49245 panagiotis
153 49790 panagiotis
        LOGGER.debug("Getting repositories by country!");
154 49898 panagiotis
        int page = 0;
155
        int size = 100;
156 50631 panagiotis
        List<Repository> resultSet = new ArrayList<>();
157 49898 panagiotis
158
        String countryCode = countriesMap.get(country);
159 49813 panagiotis
        String filterKey = "UNKNOWN";
160 51525 panagiotis
        if (mode.equalsIgnoreCase("opendoar"))
161 49813 panagiotis
            filterKey = "openaire____::opendoar";
162 51525 panagiotis
        else if (mode.equalsIgnoreCase("re3data"))
163 49813 panagiotis
            filterKey = "openaire____::re3data";
164 49431 panagiotis
165 51525 panagiotis
166 49790 panagiotis
        LOGGER.debug("Country code equals : " + countryCode);
167 49813 panagiotis
        LOGGER.debug("Filter mode equals : " + filterKey);
168 51525 panagiotis
169 50631 panagiotis
        UriComponents uriComponents = searchDatasource(String.valueOf(page),String.valueOf(size));
170
        RequestFilter requestFilter = new RequestFilter();
171
        requestFilter.setCountry(countryCode);
172 49245 panagiotis
173 51831 panagiotis
        try{
174
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
175
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
176
            while (jsonArray.length() > 0 ) {
177
                resultSet.addAll(this.getRepositoriesByMode(filterKey, Converter.jsonToRepositoryList(new JSONObject(rs))));
178
                page += 1;
179
                uriComponents = searchDatasource(String.valueOf(page),String.valueOf(size));
180
                rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
181
                jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
182
            }
183
            for (Repository r : resultSet)
184 52781 panagiotis
                this.updateRepositoryInfo(r);
185 51831 panagiotis
186
            return resultSet;
187
        }catch (Exception e){
188
            LOGGER.debug("Exception on getRepositoriesByCountry" , e);
189
            emailUtils.reportException(e);
190
            throw e;
191 49431 panagiotis
        }
192 50075 panagiotis
193 51831 panagiotis
194 49236 panagiotis
    }
195
196 52781 panagiotis
    private Repository updateRepositoryInfo(Repository r) throws JSONException {
197 51549 panagiotis
198
        /*
199
        * from datasource class
200
        * we get the datasource type form the inverted map
201
        * */
202
        r.setDatasourceType(getRepositoryType(r.getDatasourceClass()));
203 50219 panagiotis
        r.setInterfaces(this.getRepositoryInterface(r.getId()));
204
        r.setPiwikInfo(piWikApi.getPiwikSiteForRepo(r.getId()));
205
        r.setCountryName(getCountryName(r.getCountryCode()));
206 52781 panagiotis
        return r;
207 50219 panagiotis
    }
208 49790 panagiotis
209 50219 panagiotis
210 49790 panagiotis
    private Collection<Repository> getRepositoriesByMode(String mode, List<Repository> rs) {
211 49431 panagiotis
212 49790 panagiotis
        List<Repository> reps = new ArrayList<>();
213 49960 panagiotis
        for (Repository r : rs) {
214 50631 panagiotis
            if (r.getCollectedFrom() != null && r.getCollectedFrom().equals(mode))
215 49790 panagiotis
                reps.add(r);
216 51525 panagiotis
217 49813 panagiotis
        }
218 49431 panagiotis
        return reps;
219
    }
220
221 49236 panagiotis
    @Override
222 51656 panagiotis
    @PreAuthorize("hasRole('ROLE_USER')")
223 49236 panagiotis
    public List<Repository> getRepositoriesOfUser(@PathVariable("userEmail") String userEmail,
224
                                                  @PathVariable("page") String page,
225 49362 panagiotis
                                                  @PathVariable("size") String size) throws JSONException {
226 49397 panagiotis
227 49975 panagiotis
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
228 50631 panagiotis
        UriComponents uriComponents = searchDatasource(page,size);
229 50614 panagiotis
        RequestFilter requestFilter = new RequestFilter();
230
        requestFilter.setRegisteredby(userEmail);
231 50845 panagiotis
232 51831 panagiotis
        try{
233
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
234 49988 panagiotis
235 51831 panagiotis
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
236
            for (Repository r : repos)
237 52781 panagiotis
                this.updateRepositoryInfo(r);
238 51831 panagiotis
239
            return repos;
240
        }catch (Exception e){
241
            LOGGER.debug("Exception on getRepositoriesOfUser" , e);
242
            emailUtils.reportException(e);
243
            throw e;
244
        }
245 49236 panagiotis
    }
246
247
    @Override
248 52781 panagiotis
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException,ResourceNotFoundException {
249 49397 panagiotis
250 50845 panagiotis
        LOGGER.debug("Retreiving repositories with id : " + id );
251 50945 panagiotis
        Repository repo = null;
252 50845 panagiotis
        UriComponents uriComponents = searchDatasource("0","100");
253
        RequestFilter requestFilter = new RequestFilter();
254
        requestFilter.setId(id);
255 51831 panagiotis
256
        try{
257
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
258
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
259 52781 panagiotis
260
            if(jsonArray.length() == 0)
261
                throw new ResourceNotFoundException();
262
263
            repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
264
            return updateRepositoryInfo(repo);
265
        }catch (JSONException e){
266 51831 panagiotis
            LOGGER.debug("Exception on getRepositoryById" , e);
267
            emailUtils.reportException(e);
268
            throw e;
269
        }
270
271 49236 panagiotis
    }
272
273 49988 panagiotis
274 49236 panagiotis
    @Override
275 52781 panagiotis
    public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
276 49763 panagiotis
277 50845 panagiotis
        LOGGER.debug("Retreiving aggregations for repository with id : " + id );
278
        UriComponents uriComponents = searchDatasource("0","100");
279
        RequestFilter requestFilter = new RequestFilter();
280
        requestFilter.setId(id);
281 49935 panagiotis
282 52781 panagiotis
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
283
284 49960 panagiotis
        try {
285 51831 panagiotis
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
286
            JSONObject repository = new JSONObject(rs);
287 52781 panagiotis
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
288
            return aggregationHistory.size() == 0? aggregationHistory : aggregationHistory.stream()
289
                                                    .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
290
                                                    .limit(20)
291
                                                    .collect(Collectors.toList());
292
        } catch (JSONException e) {
293
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
294
            emailUtils.reportException(e);
295
            throw e;
296
        }
297 51831 panagiotis
298 52781 panagiotis
    }
299
300
    @Override
301
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
302
        LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id );
303
        UriComponents uriComponents = searchDatasource("0","100");
304
        RequestFilter requestFilter = new RequestFilter();
305
        requestFilter.setId(id);
306
307
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
308
        Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
309
        try {
310
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
311
            JSONObject repository = new JSONObject(rs);
312
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
313
            return aggregationHistory.size() == 0? aggregationByYear:createYearMap(aggregationHistory);
314
315 49960 panagiotis
        } catch (JSONException e) {
316 51831 panagiotis
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
317
            emailUtils.reportException(e);
318 49935 panagiotis
            throw e;
319
        }
320 52781 panagiotis
    }
321 49935 panagiotis
322 52781 panagiotis
    private Map<String,List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
323
        Map<String, List<AggregationDetails>> aggregationByYear;
324
        aggregationHistory = aggregationHistory.stream()
325
                            .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
326
                            .collect(Collectors.toList());
327
328
       return aggregationHistory.stream()
329
                            .collect(Collectors.groupingBy(AggregationDetails::getYear));
330 49763 panagiotis
    }
331
332 52781 panagiotis
333 49763 panagiotis
    @Override
334 49236 panagiotis
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
335
                                                  @PathVariable("page") String page,
336 49362 panagiotis
                                                  @PathVariable("size") String size) throws JSONException {
337 49397 panagiotis
338 50845 panagiotis
        LOGGER.debug("Retreiving  repositories with official name : " + name );
339
        UriComponents uriComponents = searchDatasource("0","100");
340
        RequestFilter requestFilter = new RequestFilter();
341
        requestFilter.setOfficialname(name);
342
343 51831 panagiotis
        try{
344
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
345
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
346
            for (Repository r : repos)
347 52781 panagiotis
                updateRepositoryInfo(r);
348 51831 panagiotis
            return repos;
349
        }catch (Exception e){
350
            LOGGER.debug("Exception on getRepositoriesByName" , e);
351
            emailUtils.reportException(e);
352
            throw e;
353
        }
354
355 49236 panagiotis
    }
356
357
    @Override
358 49988 panagiotis
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
359 49397 panagiotis
360
        UriComponents uriComponents = UriComponentsBuilder
361 49813 panagiotis
                .fromHttpUrl(baseAddress + "/ds/api/")
362 51330 panagiotis
                .path("/{id}")
363 49397 panagiotis
                .build().expand(id).encode();
364
365 51831 panagiotis
        try{
366
            String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
367
            return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
368
        }catch (Exception e ){
369
            LOGGER.debug("Exception on getRepositoryInterface" , e);
370
            emailUtils.reportException(e);
371
            throw e;
372
        }
373
374 49236 panagiotis
    }
375
376
    @Override
377 52781 panagiotis
    @PreAuthorize("hasRole('ROLE_USER') and #repository.registeredBy == authentication.userInfo.email")
378 50945 panagiotis
    public Repository addRepository(@RequestParam("datatype") String datatype,
379
                                    @RequestBody Repository repository) throws Exception {
380 49898 panagiotis
381 49963 panagiotis
        repository = this.setRepositoryFeatures(datatype,repository);
382 49960 panagiotis
        LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId());
383 51525 panagiotis
        this.storeRepository(repository);
384 50945 panagiotis
        return repository;
385 49963 panagiotis
    }
386 49960 panagiotis
387 51239 panagiotis
    @Override
388 52781 panagiotis
    @PreAuthorize("hasRole('ROLE_USER') and #repository.registeredBy == authentication.userInfo.email")
389 51330 panagiotis
    public Repository updateRepository(@RequestBody Repository repository) throws JSONException {
390
        UriComponents uriComponents = UriComponentsBuilder
391 51239 panagiotis
                .fromHttpUrl(baseAddress + "/ds/update/")
392
                .build()
393 51330 panagiotis
                .encode();
394 51586 panagiotis
395 51831 panagiotis
        try {
396
            String json_repository = Converter.repositoryObjectToJson(repository);
397
            HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
398
            restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
399
            return repository;
400
        }catch (Exception e){
401
            LOGGER.debug("Exception on updateRepository" , e);
402
            emailUtils.reportException(e);
403
            throw e;
404
        }
405 51586 panagiotis
406 50075 panagiotis
    }
407
408 49963 panagiotis
    private Repository setRepositoryFeatures(String datatype, Repository repository) {
409 49960 panagiotis
410 49963 panagiotis
        //TODO update map
411
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
412
        repository.setActivationId(UUID.randomUUID().toString());
413 51549 panagiotis
        repository.setCollectedFrom("infrastruct_::openaire");
414 49963 panagiotis
415 51549 panagiotis
        if (datatype.equals("journal")) {
416 49963 panagiotis
            repository.setId("openaire____::issn" + repository.getIssn());
417
            repository.setNamespacePrefix("issn" + repository.getIssn());
418 51549 panagiotis
        }else if (datatype.equals("aggregator")) {
419 49963 panagiotis
            repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
420 51549 panagiotis
            repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0,12));
421 49960 panagiotis
        }
422 51549 panagiotis
423 49963 panagiotis
        return repository;
424 49960 panagiotis
    }
425
426 49963 panagiotis
    private void updateInterface(String datatype,RepositoryInterface iFace) {
427
        //TODO call update base url
428
        //((DatasourceManagerService) this.dmService.getService()).updateBaseUrl(repo.getId(), iFace.getId(), iFace.getBaseUrl());
429
        if (!iFace.getAccessSet().isEmpty()) {
430
            LOGGER.debug("set not empty: " + iFace.getAccessSet());
431
            //TODO call update method for access params
432
            // ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "set", iFace.getAccessSet(), false);
433
        } else {
434
            //TODO call deleteAccessParamOrExtraField
435
            //((DatasourceManagerService) this.dmService.getService()).deleteAccessParamOrExtraField(repo.getId(), iFace.getId(), "set");
436
        }
437
        //TODO update content description
438
        //((DatasourceManagerService) this.dmService.getService()).updateContentDescription(repo.getId(), iFace.getId(), "metadata");
439
        if (datatype.equals("re3data")) {
440
            //TODO call update access params
441
            //  ((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_datacite", false);
442
            iFace.setAccessFormat("oai_datacite");
443
        } else {
444
            //TODO call update access params
445
            //((DatasourceManagerService) this.dmService.getService()).updateAccessParam(repo.getId(), iFace.getId(), "format", "oai_dc", false);
446
            iFace.setAccessFormat("oai_dc");
447
        }
448
449
    }
450
451 49960 panagiotis
    private void storeRepository(Repository repository) throws JSONException {
452
453 49963 panagiotis
        Date utilDate = new Date();
454
        Timestamp date = new Timestamp(utilDate.getTime());
455
        repository.setDateOfCollection(date);
456
        repository.setAggregator("OPENAIRE");
457 51525 panagiotis
        repository.setCountryCode(countriesMap.get(repository.getCountryName()));
458 49963 panagiotis
459 49397 panagiotis
        UriComponents uriComponents = UriComponentsBuilder
460
                .fromHttpUrl(baseAddress + "/ds/add/")
461
                .build()
462
                .encode();
463 50051 panagiotis
        String json_repository = Converter.repositoryObjectToJson(repository);
464 51549 panagiotis
465
        ObjectMapper mapper = new ObjectMapper();
466
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
467
        try {
468
            LOGGER.debug(mapper.writeValueAsString(json_repository));
469
        } catch (JsonProcessingException e) {
470
            e.printStackTrace();
471
        }
472
473 50051 panagiotis
        HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
474
        restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
475 49236 panagiotis
    }
476
477
    @Override
478 52781 panagiotis
    @PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
479
    public void deleteRepositoryInterface(@RequestParam("id") String id ,
480
                                          @RequestParam("registeredBy") String registeredBy){
481 49397 panagiotis
        UriComponents uriComponents = UriComponentsBuilder
482 49813 panagiotis
                .fromHttpUrl(baseAddress + "/ds/api/")
483 51525 panagiotis
                .path("/{id}")
484 49813 panagiotis
                .build().expand(id).encode();
485 51525 panagiotis
        LOGGER.debug(uriComponents.toUri());
486 49813 panagiotis
        restTemplate.delete(uriComponents.toUri());
487
    }
488
489
    @Override
490 52781 panagiotis
    @PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
491 50075 panagiotis
    public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
492
                                                      @RequestParam("repoId") String repoId,
493 52781 panagiotis
                                                      @RequestParam("registeredBy") String registeredBy,
494
                                                      @RequestBody RepositoryInterface repositoryInterface) throws JSONException,ResourceNotFoundException {
495 49963 panagiotis
        try {
496 51525 panagiotis
            Repository e = this.getRepositoryById(repoId);
497
            repositoryInterface = createRepositoryInterface(e,repositoryInterface,datatype);
498
            String json_interface = Converter.repositoryInterfaceObjectToJson(e,repositoryInterface);
499 49963 panagiotis
500
            UriComponents uriComponents = UriComponentsBuilder
501
                    .fromHttpUrl(baseAddress + "/ds/api/add/")
502
                    .build()
503
                    .encode();
504
505 50051 panagiotis
            HttpEntity<String> httpEntity = new HttpEntity <String> (json_interface,httpHeaders);
506
            restTemplate.postForObject(uriComponents.toUri(),httpEntity,String.class);
507 51525 panagiotis
            return repositoryInterface;
508 50051 panagiotis
509 51831 panagiotis
        } catch (JSONException e) {
510
            LOGGER.debug("Exception on addRepositoryInterface" , e);
511
            emailUtils.reportException(e);
512
            throw e;
513 49963 panagiotis
        }
514
    }
515
516 51525 panagiotis
    private RepositoryInterface createRepositoryInterface(Repository repo, RepositoryInterface iFace, String datatype) {
517
518
        iFace.setContentDescription("metadata");
519
        iFace.setCompliance("UNKNOWN");
520
521
        if (datatype.equals("re3data"))
522
            iFace.setAccessFormat("oai_datacite");
523
        else
524
            iFace.setAccessFormat("oai_dc");
525
526
527
        if (repo.getDatasourceClass() != null && !repo.getDatasourceClass().isEmpty())
528
            iFace.setTypology(repo.getDatasourceClass());
529
        else if (datatype.equalsIgnoreCase("journal"))
530
            iFace.setTypology("pubsrepository::journal");
531
        else if (datatype.equalsIgnoreCase("aggregator"))
532
            iFace.setTypology("aggregator::pubsrepository::unknown");
533
        else if (datatype.equalsIgnoreCase("opendoar"))
534
            iFace.setTypology("pubsrepository::unknown");
535
        else if (datatype.equalsIgnoreCase("re3data"))
536
            iFace.setTypology("datarepository::unknown");
537
538
        iFace.setRemovable(true);
539
        iFace.setAccessProtocol("oai");
540
        iFace.setMetadataIdentifierPath("//*[local-name()='header']/*[local-name()='identifier']");
541
        iFace.setId("api_________::" + repo.getId() + "::" + UUID.randomUUID().toString().substring(0, 8));
542
        if (iFace.getAccessSet().isEmpty()) {
543
            LOGGER.debug("set is empty: " + iFace.getAccessSet());
544
            iFace.removeAccessSet();
545
        }
546
        return iFace;
547
    }
548
549 49236 panagiotis
    @Override
550
    public List<String> getDnetCountries() {
551 49770 panagiotis
        LOGGER.debug("Getting dnet-countries!");
552 49236 panagiotis
        return Converter.readFile("countries.txt");
553
    }
554
555
    @Override
556
    public List<String> getTypologies() {
557
        return Converter.readFile("typologies.txt");
558
    }
559
560
    @Override
561 49763 panagiotis
    public List<Timezone> getTimezones() {
562
        List<String> timezones =  Converter.readFile("timezones.txt");
563
        return Converter.toTimezones(timezones);
564 49236 panagiotis
    }
565
566
    @Override
567 51656 panagiotis
    @PreAuthorize("hasRole('ROLE_USER')")
568 50614 panagiotis
    public List<String> getUrlsOfUserRepos(@PathVariable("user_email") String userEmail,
569 49763 panagiotis
                                           @PathVariable("page") String page,
570
                                           @PathVariable("size") String size) throws JSONException {
571
        UriComponents uriComponents = UriComponentsBuilder
572
                .fromHttpUrl(baseAddress + "/api/baseurl/")
573
                .path("/{page}/{size}")
574
                .build().expand(page,size).encode();
575 50614 panagiotis
576 51831 panagiotis
        try{
577
            RequestFilter requestFilter = new RequestFilter();
578
            requestFilter.setRegisteredby(userEmail);
579
            return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(),requestFilter, String[].class));
580
        }catch (Exception e){
581
            LOGGER.debug("Exception on addRepositoryInterface" , e);
582
            emailUtils.reportException(e);
583
            throw e;
584
        }
585 49236 panagiotis
    }
586
587 49450 panagiotis
    @Override
588
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
589
590
        List<String> resultSet = new ArrayList<>();
591
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
592
            if (mode.equalsIgnoreCase("aggregator")) {
593
                if (entry.getKey().contains("aggregator"))
594
                    resultSet.add(entry.getValue());
595
            } else if (mode.equalsIgnoreCase("journal")) {
596
                if (entry.getKey().contains("journal"))
597
                    resultSet.add(entry.getValue());
598
            } else if (mode.equalsIgnoreCase("opendoar")) {
599
                if (entry.getKey().contains("pubsrepository"))
600
                    resultSet.add(entry.getValue());
601
            } else if (mode.equalsIgnoreCase("re3data")) {
602
                if (entry.getKey().contains("datarepository"))
603
                    resultSet.add(entry.getValue());
604
            }
605
        }
606
607
608
        return resultSet;
609
    }
610
611
    private Vocabulary getVocabulary(String vocName) {
612
613
        if (!vocabularyMap.containsKey(vocName)) {
614
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
615
        }
616
        return vocabularyMap.get(vocName);
617
    }
618
619 49790 panagiotis
620
    @Override
621
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode)  {
622
623
        LOGGER.debug("Getting compatibility classes for mode: " + mode);
624
        Map<String, String> retMap = new HashMap<String, String>();
625
626
        Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
627
        boolean foundData = false;
628
        for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
629
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
630
                return compatibilityClasses;
631
            else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
632
                if (entry.getKey().matches("^openaire[1-9].0_data$")) {
633
                    retMap.put(entry.getKey(), entry.getValue());
634
                    foundData = true;
635
                }
636
            } else {
637
                if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
638
                    retMap.put(entry.getKey(), entry.getValue());
639
            }
640
        }
641
642
        //TODO TO BE REMOVED WHEN VOCABULARIES ARE UPDATED
643
        if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA) && !foundData)
644
            retMap.put("openaire2.0_data", "OpenAIRE Data (funded, referenced datasets)");
645
646
        return retMap;
647
    }
648
649
    @Override
650
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode)  {
651
652
        LOGGER.debug("Getting datasource classes for mode: " + mode);
653
654
        Map<String, String> retMap = new HashMap<String, String>();
655
656
        for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
657
            if (mode.equalsIgnoreCase("aggregator")) {
658
                if (entry.getKey().contains("aggregator"))
659
                    retMap.put(entry.getKey(), entry.getValue());
660
            } else if (mode.equalsIgnoreCase("journal")) {
661
                if (entry.getKey().contains("journal"))
662
                    retMap.put(entry.getKey(), entry.getValue());
663
            } else if (mode.equalsIgnoreCase("opendoar")) {
664
                if (entry.getKey().contains("pubsrepository"))
665
                    retMap.put(entry.getKey(), entry.getValue());
666
            } else if (mode.equalsIgnoreCase("re3data")) {
667
                if (entry.getKey().contains("datarepository"))
668
                    retMap.put(entry.getKey(), entry.getValue());
669
            }
670
        }
671 51549 panagiotis
        return filterResults(retMap,mode);
672 49790 panagiotis
673
    }
674
675 51549 panagiotis
    private Map<String,String> filterResults(Map<String, String> map,String mode) {
676
677
        HashMap<String,String> filteredMap = new HashMap<>();
678
        for(String key:map.keySet())
679
            if(dataSourceClass.get(mode).contains(key))
680
                filteredMap.put(key,map.get(key));
681
682
        return filteredMap;
683
    }
684
685 49898 panagiotis
    @Override
686
    public String getCountryName(String countryCode) {
687
        return inverseCountriesMap.get(countryCode);
688
    }
689
690 50570 panagiotis
    @Override
691
    public MetricsInfo getMetricsInfoForRepository(@PathVariable("repoId")  String repoId) throws RepositoryServiceException {
692
        try {
693
694
            MetricsInfo metricsInfo = new MetricsInfo();
695
            metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
696
            metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
697
            return metricsInfo;
698
699
        } catch (Exception e) {
700
            LOGGER.error("Error while getting metrics info for repository: ", e);
701 51831 panagiotis
            emailUtils.reportException(e);
702 50570 panagiotis
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
703
        }
704
    }
705
706 51330 panagiotis
    @Override
707
    public Map<String, String> getListLatestUpdate(@PathVariable("mode")  String mode) throws JSONException {
708
        if(mode.equals("opendoar"))
709
            return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(0).getLastCollectionDate());
710
        else
711
            /*
712
            * first api of re3data has null value on collection date
713
            * */
714
            return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(1).getLastCollectionDate());
715
    }
716
717 51525 panagiotis
    @Override
718 52781 panagiotis
    @PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
719 51525 panagiotis
    public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String repoId,
720 52781 panagiotis
                                                         @RequestParam("registeredBy") String registeredBy,
721 51525 panagiotis
                                                         @RequestBody RepositoryInterface repositoryInterface) throws JSONException {
722
723
        this.updateBaseUrl(repoId,repositoryInterface.getId(),repositoryInterface.getBaseUrl());
724
        this.updateCompliance(repoId,repositoryInterface.getId(),repositoryInterface.getCompliance());
725 51549 panagiotis
        this.updateValidationSet(repoId,repositoryInterface.getId(),repositoryInterface.getAccessSet());
726 51525 panagiotis
        return repositoryInterface;
727
    }
728
729 51549 panagiotis
    private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) {
730
        UriComponents uriComponents = UriComponentsBuilder
731
                .fromHttpUrl(baseAddress + "/ds/api/oaiset")
732
                .queryParam("dsId",repositoryId)
733
                .queryParam("apiId",repositoryInterfaceId)
734
                .queryParam("oaiSet",validationSet)
735
                .build().encode();
736
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
737
    }
738 51525 panagiotis
739 51549 panagiotis
740 51525 panagiotis
    private void updateBaseUrl(String repositoryId, String repositoryInterfaceId, String baseUrl) {
741
        UriComponents uriComponents = UriComponentsBuilder
742
                .fromHttpUrl(baseAddress + "/ds/api/baseurl")
743
                .queryParam("dsId",repositoryId)
744
                .queryParam("apiId",repositoryInterfaceId)
745
                .queryParam("baseUrl",baseUrl)
746
                .build().encode();
747
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
748
    }
749
750
    private void updateCompliance(String repositoryId, String repositoryInterfaceId,String compliance) {
751
        UriComponents uriComponents = UriComponentsBuilder
752
                .fromHttpUrl(baseAddress + "/ds/api/compliance")
753
                .queryParam("dsId",repositoryId)
754
                .queryParam("apiId",repositoryInterfaceId)
755
                .queryParam("compliance",compliance)
756
                .build().encode();
757
        restTemplate.postForObject(uriComponents.toUri(),null,String.class);
758
    }
759
760 50570 panagiotis
    private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
761
762
        //build the uri params
763
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
764
765
        //create new template engine
766
        RestTemplate template = new RestTemplate();
767
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
768
        ResponseEntity<MetricsNumbers> resp;
769
        try {
770
            //communicate with endpoint
771
            resp = template.exchange(
772
                    builder.build().encode().toUri(),
773
                    HttpMethod.GET,
774
                    null,
775
                    new ParameterizedTypeReference<MetricsNumbers>() {
776
                    });
777
        } catch (RestClientException e) {
778 51831 panagiotis
            LOGGER.debug("Exception on getMetricsNumbers" , e);
779
            emailUtils.reportException(e);
780 50570 panagiotis
            throw e;
781
        }
782
783
        return resp.getBody();
784
    }
785
786
    private String getOpenAIREId(String repoId) {
787
788
        if (repoId != null && repoId.contains("::")) {
789
            return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
790
        }
791
792
        return null;
793
    }
794
795 50631 panagiotis
    private UriComponents searchDatasource(String page,String size){
796 50570 panagiotis
797 50631 panagiotis
        return UriComponentsBuilder
798
                .fromHttpUrl(baseAddress + "/ds/search/")
799
                .path("/{page}/{size}/")
800
                .queryParam("requestSortBy","id")
801
                .queryParam("order","ASCENDING")
802
                .build().expand(page, size).encode();
803
    }
804
805 51549 panagiotis
    private String getRepositoryType(String typology){
806
        return invertedDataSourceClass.get(typology);
807
    }
808 50631 panagiotis
809 51549 panagiotis
810 49236 panagiotis
}