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