Project

General

Profile

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