Project

General

Profile

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