Project

General

Profile

1
package eu.dnetlib.repo.manager.server.services;
2

    
3
import com.fasterxml.jackson.databind.DeserializationConfig;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
6
import com.unboundid.util.Base64;
7
import eu.dnetlib.domain.data.PiwikInfo;
8
import eu.dnetlib.domain.data.Repository;
9
import eu.dnetlib.domain.data.RepositoryInterface;
10
import eu.dnetlib.domain.enabling.Vocabulary;
11
import eu.dnetlib.domain.functionality.UserProfile;
12
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
13
import eu.dnetlib.repo.manager.client.services.RepositoryService;
14
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
15
import eu.dnetlib.repo.manager.server.utils.LocalVocabularies;
16
import eu.dnetlib.domain.data.PiwikInfo;
17
import eu.dnetlib.repo.manager.service.controllers.RepositoryApi;
18
import eu.dnetlib.repo.manager.shared.*;
19
import eu.dnetlib.repos.RepoApi;
20
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
21
import org.apache.commons.codec.digest.DigestUtils;
22
import org.apache.commons.lang.StringEscapeUtils;
23
import org.apache.commons.lang.WordUtils;
24
import org.apache.log4j.Logger;
25
import org.json.JSONException;
26
import org.json.JSONObject;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.beans.factory.annotation.Value;
29
import org.springframework.core.ParameterizedTypeReference;
30
import org.springframework.dao.EmptyResultDataAccessException;
31
import org.springframework.http.HttpMethod;
32
import org.springframework.http.ResponseEntity;
33
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
34
import org.springframework.scheduling.annotation.Scheduled;
35
import org.springframework.stereotype.Service;
36
import org.springframework.web.client.RestClientException;
37
import org.springframework.web.client.RestTemplate;
38
import org.springframework.web.util.UriComponentsBuilder;
39

    
40
import javax.annotation.PostConstruct;
41
import java.io.IOException;
42
import java.io.UnsupportedEncodingException;
43
import java.net.URLEncoder;
44
import java.text.Normalizer;
45
import java.util.*;
46
import java.util.concurrent.ConcurrentHashMap;
47
import java.net.URL;
48

    
49
/**
50
 * Created by nikonas on 12/8/15.
51
 */
52
@SuppressWarnings("serial")
53
@Service("repositoryService")
54
public class RepositoryServiceImpl extends SpringGwtRemoteServiceServlet implements RepositoryService {
55

    
56
    private static final Logger LOGGER = Logger
57
            .getLogger(RepositoryServiceImpl.class);
58

    
59
    @Autowired
60
    private RepoApi repoAPI;
61

    
62
    @Autowired
63
    private EmailUtils emailUtils;
64

    
65
    private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
66

    
67
    @Autowired
68
    private VocabularyLoader vocabularyLoader;
69

    
70
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
71

    
72
    @Value("${services.repo-manager.repository.testing.mode}")
73
    private boolean testingMode;
74

    
75
    @Autowired
76
    private PiwikDAO piwikDAO;
77

    
78
    @Value("${services.repomanager.analyticsURL}")
79
    private String analyticsURL;
80

    
81
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
82
    private String usageStatisticsDiagramsBaseURL;
83

    
84
    @Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
85
    private String usageStatisticsNumbersBaseURL;
86

    
87
    private static final String PIWIK_SCRIPT = StringEscapeUtils.escapeHtml("<!-- Piwik -->\n" +
88
            "<script type=\"text/javascript\">\n" +
89
            "\tvar _paq = _paq || [];\n" +
90
            "\t_paq.push(['enableLinkTracking']);\n" +
91
            "\t(function() {\n" +
92
            "\t\tvar u=\"//analytics.openaire.eu/\";\n" +
93
            "\t\t_paq.push(['setTrackerUrl', u+'piwik.php']);\n" +
94
            "\t\t_paq.push(['setSiteId', $$$]);\n" +
95
            "\t\t<% if(handle != null){%>\n" +
96
            "\t\t\t_paq.push(['setCustomVariable', 1, 'oaipmhID',\"oai:<%= baseUrl %>:<%=handle %>\", 'page']);\n" +
97
            "\t\t\t_paq.push(['trackPageView']);\n" +
98
            "\t\t<}>\n" +
99
            "\t\tvar d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n" +
100
            "\t\tg.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);\n" +
101
            "\t})();\n" +
102
            "</script>\n" +
103
            "<noscript>\n" +
104
            "\t<p>\n" +
105
            "\t\t<img src=\"//analytics.openaire.eu/piwik.php?idsite=47\" style=\"border:0;\" alt=\"\" />\n" +
106
            "\t</p>\n" +
107
            "</noscript>\n" +
108
            "<!— End Piwik Code —>");
109

    
110

    
111
    @Autowired
112
    private RepositoryApi repositoryApi;
113

    
114

    
115

    
116
    @PostConstruct
117
    public void init() {
118
        this.loadVocabularies();
119
    }
120

    
121
    @Override
122
    public Tuple<List<Repository>, List<Repository>> getRepositoriesByCountry(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
123
        try {
124
            if (testingMode)
125
                return this.getRepositoriesByCountryTesting(country, mode, includeUnknownCountries);
126
            LOGGER.debug("Getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
127

    
128
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
129
//            List<Repository> reposList = this.repoAPI.getRepositoriesPerCountry(mode).get(country);
130

    
131
            Boolean managed = null;
132
            List<Repository> reposList = repositoryApi.getRepositoriesByCountry(country,mode,managed);
133
            if (reposList == null) {
134
                retTuple.setFirst(new ArrayList<Repository>());
135
//                if (!includeUnknownCountries) {
136
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
137
//                }
138
            } else {
139
                retTuple.setFirst(reposList);
140
            }
141

    
142
            if (includeUnknownCountries) {
143
                List<Repository> withoutCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("Without Country");
144
                List<Repository> unknownCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("UNKNOWN");
145
                List<Repository> totalList = new ArrayList<Repository>();
146
                if (withoutCountryList != null)
147
                    totalList.addAll(withoutCountryList);
148
                if (unknownCountryList != null)
149
                    totalList.addAll(unknownCountryList);
150
                retTuple.setSecond(totalList);
151
            }
152

    
153
            return retTuple;
154

    
155
        } catch (Exception e) {
156
            LOGGER.error("Error while getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
157
            if (e instanceof RepositoryServiceException) {
158
                throw (RepositoryServiceException) e;
159
            } else {
160
                emailUtils.reportException(e);
161
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
162
            }
163
        }
164
    }
165

    
166
    @Override
167
    public List<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
168
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
169
    }
170

    
171
    @Override
172
    public DatasourcesCollection getRepositoriesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
173

    
174
        DatasourcesCollection retDatasources = new DatasourcesCollection();
175
        try {
176
            LOGGER.debug("Getting repositories of user: " + userEmail + " . IncludeShared: "
177
                    + includeShared + " . IncludeByOthers: " + includeByOthers);
178
            int page = 0;
179
            String size = "50";
180
            List<Repository> resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
181
            while(resultSet.size() > 0 ){
182
                retDatasources.getDatasourcesOfUser().addAll(resultSet);
183
                page++;
184
                resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
185
            }
186

    
187
/*
188
	if (includeShared) {
189
                //TODO create dao to save-get shared datasourcesIDs
190
                List<String> sharedDatasourceIds = new ArrayList<String>();
191
                retDatasources.setSharedDatasources(this.repoAPI.getReposByIds(sharedDatasourceIds));
192
                //geting Piwik Info
193
                for(Repository repository: retDatasources.getSharedDatasources())
194
                    repository.setPiwikInfo(this.getPiwikSiteForRepository(repository.getId()));
195
            }
196

    
197
            if (includeByOthers) {
198
                retDatasources.setDatasourcesOfOthers(this.repoAPI.getRepositoriesOfUser(userEmail, true));
199
                //geting Piwik Info
200
                for(Repository repository: retDatasources.getDatasourcesOfOthers())
201
                    repository.setPiwikInfo(this.getPiwikSiteForRepository(repository.getId()));
202
            }
203
*/
204
        } catch (JSONException e) {
205
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
206
            emailUtils.reportException(e);
207
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
208
        }
209
        return retDatasources;
210
    }
211

    
212
    @Override
213
    public List<String> getRepositoryUrlsOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
214
        try {
215
            LOGGER.debug("Getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
216
            List<String> retRepos = new ArrayList<String>();
217

    
218
            int page = 0;
219
            String size = "50";
220
            List<String> resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
221
            while(resultSet.size() > 0 ){
222
                retRepos.addAll(resultSet);
223
                page++;
224
                resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
225
            }
226
            return retRepos;
227

    
228
        } catch (Exception e) {
229
            LOGGER.error("Error while getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
230
            emailUtils.reportException(e);
231
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
232
        }
233
    }
234

    
235
    @Override
236
    public Repository getRepository(String repoId) throws RepositoryServiceException {
237
        try {
238
            LOGGER.debug("Getting repository with id: " + repoId);
239
            Repository repo = repositoryApi.getRepositoryById(repoId);
240

    
241
            if (repo != null) {
242
                for (RepositoryInterface iFace : repo.getInterfaces()) {
243
                    if (!iFace.getContentDescription().equals("file::hybrid") && iFace.getAccessProtocol().equalsIgnoreCase("oai")) {
244
                        iFace.setComplianceName(getComplianceName(iFace.getCompliance()));
245
                        if (iFace.getCompliance().equals("notCompatible"))
246
                            iFace.setComplianceName("not compatible");
247
                    }
248
                }
249

    
250
                //geting Piwik Info
251
                repo.setPiwikInfo(this.getPiwikSiteForRepository(repoId));
252

    
253
            } else
254
                throw new RepositoryServiceException("registration.repositoryNotExists", RepositoryServiceException.ErrorCode.REPOSITORY_NOT_EXISTS);
255
            return repo;
256

    
257
        } catch (Exception e) {
258
            LOGGER.error("Error while getting repository with id: " + repoId, e);
259
            if (e instanceof RepositoryServiceException) {
260
                throw (RepositoryServiceException) e;
261
            } else {
262
                emailUtils.reportException(e);
263
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
264
            }
265
        }
266
    }
267

    
268
    @Override
269
    public Map<String, String> getCountries(Boolean existingOnly, String mode) throws RepositoryServiceException {
270
        try {
271
            LOGGER.debug("Getting countries");
272
            List<String> countries = new ArrayList<String>();
273

    
274
            Map<String, String> countriesMap = new TreeMap<String, String>();
275

    
276
            if (existingOnly) {
277
                LOGGER.debug("using the repositories map");
278
                countries.addAll(this.repoAPI.getRepositoriesByCountry(mode).keySet());
279
            } else {
280
                LOGGER.debug("using \"dnet:countries\" vocabulary");
281
                countries.addAll(this.getVocabulary("dnet:countries").getEnglishNames());
282
            }
283
//            countries.addAll(repositoryApi.getDnetCountries());
284
            for (String country : countries) {
285
                countriesMap.put(country, WordUtils.capitalizeFully(country));
286
            }
287

    
288
            return countriesMap;
289

    
290
        } catch (Exception e) {
291
            LOGGER.error("Error while getting getting countries", e);
292
            if (e instanceof RepositoryServiceException) {
293
                throw (RepositoryServiceException) e;
294
            } else {
295
                emailUtils.reportException(e);
296
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
297
            }
298
        }
299
    }
300

    
301
    @Override
302
    public Map<String, String> getCountries() throws RepositoryServiceException {
303
        return this.getCountries(false, null);
304
    }
305

    
306
    @Override
307
    public List<Timezone> getTimezones() throws RepositoryServiceException {
308
        try {
309
            LOGGER.debug("Getting timezones from file");
310
//            return repositoryApi.getTimezones();
311
            return LocalVocabularies.timezones;
312
        } catch (Exception e) {
313
            LOGGER.error("Error while getting timezones from file", e);
314
            emailUtils.reportException(e);
315
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
316
        }
317

    
318
    }
319

    
320
    @Override
321
    public List<String> getTypologies() throws RepositoryServiceException {
322
        try {
323
            LOGGER.debug("Getting typologies from file");
324
           // return repositoryApi.getTypologies();
325
            return LocalVocabularies.typologies;
326
        } catch (Exception e) {
327
            LOGGER.error("Error while getting typologies from file", e);
328
            emailUtils.reportException(e);
329
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
330
        }
331
    }
332

    
333
    @Override
334
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
335
        return repositoryApi.getDatasourceClasses(mode);
336
    }
337

    
338
    @Override
339
    public Map<String, String> getCompatibilityClasses(String mode) throws RepositoryServiceException {
340
        return repositoryApi.getCompatibilityClasses(mode);
341
    }
342

    
343
    @Override
344
    public void storeRepository(Repository repo, String mode) throws RepositoryServiceException {
345

    
346
        try {
347
           /* LOGGER.debug("Storing repository with name: " + repo.getOfficialName());
348
            //List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
349
            JSONObject params = new JSONObject();
350
            params.put("datatype", mode);
351
            ObjectMapper mapper = new ObjectMapper();
352
            String json_repo = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repo);
353
            params.put("repository", json_repo);*/
354

    
355

    
356
            //repositoryApi.addRepository(params.toString());
357
            repositoryApi.addRepository(mode,repo);
358
            LOGGER.debug("Repository with name: " + repo.getOfficialName() + " stored!");
359

    
360
        }catch (Exception e) {
361
            emailUtils.reportException(e);
362
            LOGGER.error("Error while storing repository with name: " + repo.getOfficialName(), e);
363
            throw new RepositoryServiceException("Error while storing repository", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
364
        }
365
    }
366

    
367
    @Override
368
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
369
        try {
370
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
371

    
372
	    //TODO SOS, check old API
373

    
374
            //this.repoAPI.updateRepositoryInformation(repo);
375
            repositoryApi.updateEnglishName(repo.getId(),repo.getEnglishName());
376
            repositoryApi.updateLatitude(repo.getId(), String.valueOf(repo.getLatitude()));
377
            repositoryApi.updateLongitude(repo.getId(), String.valueOf(repo.getLongitude()));
378
            repositoryApi.updateOfficialName(repo.getId(),repo.getOfficialName());
379
            repositoryApi.updateLogoUrl(repo.getId(),repo.getLogoUrl());
380
            repositoryApi.updateTimezone(repo.getId(),String.valueOf(repo.getTimezone()));
381
            repositoryApi.updatePlatform(repo.getId(),repo.getTypology());
382

    
383
        } catch (Exception e) {
384
            LOGGER.error("Error while updating information of repo: " + repo.getOfficialName(), e);
385
            if (e instanceof RepositoryServiceException) {
386
                throw (RepositoryServiceException) e;
387
            } else {
388
                emailUtils.reportException(e);
389
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
390
            }
391
        }
392
    }
393

    
394
    @Override
395
    public RepositoryInterface updateInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
396
        try {
397
            LOGGER.debug("updating interface with id: " + iFace.getId());
398
            RepositoryInterface retIface = null;
399
            retIface = this.repoAPI.updateRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
400
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
401

    
402
            return retIface;
403
        } catch (Exception e) {
404
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
405
            if (e instanceof RepositoryServiceException) {
406
                throw (RepositoryServiceException) e;
407
            } else {
408
                emailUtils.reportException(e);
409
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
410
            }
411
        }
412
    }
413

    
414
    @Override
415
    public RepositoryInterface insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
416
        try {
417
            LOGGER.debug("inserting interface with id: " + iFace.getId());
418
            RepositoryInterface retIface = null;
419
            //retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
420

    
421
          /*  JSONObject params = new JSONObject();
422
            params.put("datatype",datatype);
423
            params.put("repoId",repoId);
424
            params.put("iFace",iFace);*/
425
            //retIface = repositoryApi.addRepositoryInterface(params.toString());
426

    
427
            retIface = repositoryApi.addRepositoryInterface(datatype,repoId,iFace);
428
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
429
            return retIface;
430

    
431
        } catch (Exception e) {
432
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
433
            if (e instanceof RepositoryServiceException) {
434
                throw (RepositoryServiceException) e;
435
            } else {
436
                emailUtils.reportException(e);
437
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
438
            }
439
        }
440
    }
441

    
442
    @Override
443
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
444
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
445
        iFaces.add(iFace);
446
        this.deleteInterfaces(repoId, iFaces, datatype);
447
    }
448

    
449
    @Override
450
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
451
        try {
452
            LOGGER.debug("deleting interfaces of repo: " + repoId);
453
            //this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
454

    
455
            for(RepositoryInterface iFace : iFaces) {
456
                LOGGER.info("deleting repository interface with url/set/id: " + iFace.getBaseUrl() + "/"
457
                        + iFace.getAccessSet() + "/" + iFace.getId());
458
                repositoryApi.deleteRepositoryInterface(iFace.getId());
459
            }
460

    
461
        } catch (Exception e) {
462
            LOGGER.error("deleting interfaces of repo: " + repoId, e);
463
            if (e instanceof RepositoryServiceException) {
464
                throw (RepositoryServiceException) e;
465
            } else {
466
                emailUtils.reportException(e);
467
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
468
            }
469
        }
470

    
471
    }
472

    
473
    @Override
474
    public DatasourceVocabularies getDatasourceVocabularies(String mode) throws RepositoryServiceException {
475
        try {
476
            LOGGER.debug("Getting vocabularies for datasource with type: " + mode);
477
            DatasourceVocabularies vocs = new DatasourceVocabularies();
478
            vocs.setCountries(this.getCountries());
479
            vocs.setDatasourceClasses(this.getDatasourceClasses(mode));
480
            vocs.setTimezones(this.getTimezones());
481
            vocs.setTypologies(this.getTypologies());
482
            vocs.setCompatibilityLevels(this.getCompatibilityClasses(mode));
483

    
484
            return vocs;
485

    
486
        } catch (Exception e) {
487
            LOGGER.error("Error while getting vocabularies for datasource with type: \" + mode", e);
488
            emailUtils.reportException(e);
489
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
490
        }
491
    }
492

    
493
    private Tuple<List<Repository>, List<Repository>> getRepositoriesByCountryTesting(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
494
        try {
495
            LOGGER.debug("Getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
496

    
497
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
498
            List<Repository> reposList = new ArrayList<Repository>();
499
            reposList.add(this.repoAPI.getRepository("opendoar____::1356"));
500
            reposList.add(this.repoAPI.getRepository("opendoar____::2678"));
501
            reposList.add(this.repoAPI.getRepository("opendoar____::2980"));
502
            reposList.add(this.repoAPI.getRepository("opendoar____::1347"));
503
            reposList.add(this.repoAPI.getRepository("opendoar____::2984"));
504

    
505
            retTuple.setFirst(reposList);
506

    
507
            if (includeUnknownCountries) {
508
                List<Repository> totalList = new ArrayList<Repository>();
509
                totalList.add(this.repoAPI.getRepository("opendoar____::3000"));
510
                totalList.add(this.repoAPI.getRepository("opendoar____::1027"));
511
                totalList.add(this.repoAPI.getRepository("opendoar____::1096"));
512

    
513
                retTuple.setSecond(totalList);
514
            }
515

    
516
            return retTuple;
517

    
518
        } catch (Exception e) {
519
            LOGGER.error("Error while getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
520
            if (e instanceof RepositoryServiceException) {
521
                throw (RepositoryServiceException) e;
522
            } else {
523
                emailUtils.reportException(e);
524
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
525
            }
526
        }
527
    }
528

    
529
    @Override
530
    public String getLatestUpdateDateOfList(String mode) throws RepositoryServiceException {
531
        try {
532
            LOGGER.debug("Getting latest update date of list: " + mode);
533
            return this.repoAPI.getListLatestUpdate(mode).split("T")[0];
534

    
535
        } catch (Exception e) {
536
            LOGGER.error("Error while getting latest update date of list: " + mode, e);
537
            emailUtils.reportException(e);
538
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
539
        }
540
    }
541

    
542
    @Override
543
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
544
        try {
545
            LOGGER.debug("Repo id -> " + repoId);
546
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
547
        } catch (EmptyResultDataAccessException e) {
548
            return null;
549
        }
550
    }
551

    
552
    @Override
553
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
554
        
555
        try {
556
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(repository.getOfficialName(), "UTF-8") + "&url=" + URLEncoder.encode(repository.getWebsiteUrl(), "UTF-8");
557
            Map<String, Object> map = new ObjectMapper().readValue(new URL(URL), Map.class);
558

    
559
            String siteId = null;
560
            if(map.get("value")!=null) {
561
                siteId = map.get("value").toString();
562
            }
563

    
564
            String authenticationToken = "32846584f571be9b57488bf4088f30ea";
565

    
566
            PiwikInfo piwikInfo = new PiwikInfo();
567
            piwikInfo.setRepositoryId(repository.getId());
568
            piwikInfo.setRepositoryName(repository.getOfficialName());
569
            piwikInfo.setCountry(repository.getCountryName());
570
            piwikInfo.setSiteId(siteId);
571
            piwikInfo.setAuthenticationToken(authenticationToken);
572
            piwikInfo.setRequestorEmail(requestor.getEmail());
573
            piwikInfo.setRequestorName(requestor.getFirstname() + " " + requestor.getLastname());
574
            piwikInfo.setValidated(false);
575

    
576
            this.piwikDAO.savePiwikInfo(piwikInfo);
577

    
578
            emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
579
            emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
580

    
581
        } catch (UnsupportedEncodingException uee) {
582
            LOGGER.error("Error while creating piwikScript URL", uee);
583
            emailUtils.reportException(uee);
584
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
585
        } catch (IOException ioe) {
586
            LOGGER.error("Error while creating piwik site", ioe);
587
            emailUtils.reportException(ioe);
588
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
589
        } catch (Exception e) {
590
            LOGGER.error("Error while sending email to administrator or user about the request to enable metrics", e);
591
            emailUtils.reportException(e);
592
        }
593
    }
594

    
595
    @Override
596
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
597
        try {
598
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
599

    
600
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
601
            return piwikScript;
602

    
603
        } catch (EmptyResultDataAccessException e) {
604
            return null;
605
        }
606
    }
607

    
608
    @Override
609
    public List<PiwikInfo> getPiwikSitesForRepositories() throws RepositoryServiceException {
610
        try {
611

    
612
            List<PiwikInfo> piwikInfos = new ArrayList<>();
613
            piwikInfos = this.piwikDAO.getPiwikSitesForRepos();
614

    
615
            return piwikInfos;
616

    
617
        } catch (EmptyResultDataAccessException e) {
618
            LOGGER.error("Error while getting list of piwik sites: ", e);
619
            emailUtils.reportException(e);
620
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
621
        }
622
    }
623

    
624
    @Override
625
    public void markPiwikSiteAsValidated(String repositoryId) throws RepositoryServiceException {
626
        try {
627
            this.piwikDAO.markPiwikSiteAsValidated(repositoryId);
628

    
629
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repositoryId);
630
            emailUtils.sendAdministratorMetricsEnabled(piwikInfo);
631
            emailUtils.sendUserMetricsEnabled(piwikInfo);
632

    
633
        } catch (EmptyResultDataAccessException e) {
634
            LOGGER.error("Error while approving piwik site: ", e);
635
            emailUtils.reportException(e);
636
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
637
        } catch (Exception e) {
638
            LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e);
639
            emailUtils.reportException(e);
640
        }
641
    }
642

    
643
    @Override
644
    public MetricsInfo getMetricsInfoForRepository(String repoId) throws RepositoryServiceException {
645
        try {
646

    
647
            MetricsInfo metricsInfo = new MetricsInfo();
648
            metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
649
            metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
650
            return metricsInfo;
651

    
652
        } catch (Exception e) {
653
            LOGGER.error("Error while getting metrics info for repository: ", e);
654
            emailUtils.reportException(e);
655
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
656
        }
657
    }
658

    
659
    private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
660

    
661
        //build the uri params
662
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
663

    
664
        //create new template engine
665
        RestTemplate template = new RestTemplate();
666
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
667
        ResponseEntity<MetricsNumbers> resp;
668
        try {
669
            //communicate with endpoint
670
            resp = template.exchange(
671
                    builder.build().encode().toUri(),
672
                    HttpMethod.GET,
673
                    null,
674
                    new ParameterizedTypeReference<MetricsNumbers>() {
675
                    });
676
        } catch (RestClientException e) {
677
            throw e;
678
        }
679

    
680
        return resp.getBody();
681
    }
682

    
683
    private String getCountryCode(String countryName) {
684
        Vocabulary countries = this.getVocabulary("dnet:countries");
685

    
686
        return countries.getEncoding(countryName);
687
    }
688

    
689
    private String getDatasourceClassCode(String datasourceClassName) {
690
        Vocabulary datasourceClasses = this.getVocabulary("dnet:datasource_typologies");
691

    
692
        return datasourceClasses.getEncoding(datasourceClassName);
693
    }
694

    
695
    private String getComplianceName(String complianceCode) {
696
        Vocabulary compatibilityLevels = this.getVocabulary("dnet:compatibilityLevel");
697

    
698
        return compatibilityLevels.getEnglishName(complianceCode);
699
    }
700

    
701
    private Vocabulary getVocabulary(String vocName) {
702

    
703
        if (!vocabularyMap.containsKey(vocName)) {
704
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
705
        }
706
        return vocabularyMap.get(vocName);
707
    }
708

    
709
    @Scheduled(fixedRate = 3600000)
710
    private void loadVocabularies() {
711
        LOGGER.debug("loading vocabularies");
712
        for (String vocName : vocabularyNames) {
713
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
714
        }
715
    }
716

    
717
    private String getOpenAIREId(String repoId) {
718

    
719
        if (repoId != null && repoId.contains("::")) {
720
            return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
721
        }
722

    
723
        return null;
724
    }
725
}
(4-4/6)