Project

General

Profile

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

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

    
35
import javax.annotation.PostConstruct;
36
import java.io.IOException;
37
import java.io.UnsupportedEncodingException;
38
import java.net.URLEncoder;
39
import java.util.*;
40
import java.util.concurrent.ConcurrentHashMap;
41
import java.net.URL;
42

    
43
/**
44
 * Created by nikonas on 12/8/15.
45
 */
46
@SuppressWarnings("serial")
47
@Service("repositoryService")
48
public class RepositoryServiceImpl extends SpringGwtRemoteServiceServlet implements RepositoryService {
49

    
50
    private static final Logger LOGGER = Logger
51
            .getLogger(RepositoryServiceImpl.class);
52

    
53
    @Autowired
54
    private RepoApi repoAPI;
55

    
56
    @Autowired
57
    private EmailUtils emailUtils;
58

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

    
61
    @Autowired
62
    private VocabularyLoader vocabularyLoader;
63

    
64
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
65

    
66
    @Value("${services.repo-manager.repository.testing.mode}")
67
    private boolean testingMode;
68

    
69
    @Autowired
70
    private PiwikDAO piwikDAO;
71

    
72
    @Value("${services.repomanager.analyticsURL}")
73
    private String analyticsURL;
74

    
75
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
76
    private String usageStatisticsDiagramsBaseURL;
77

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

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

    
104

    
105
    @Autowired
106
    private RepositoryApi repositoryApi;
107

    
108

    
109

    
110
    @PostConstruct
111
    public void init() {
112
        this.loadVocabularies();
113
    }
114

    
115
    @Override
116
    public Tuple<List<Repository>, List<Repository>> getRepositoriesByCountry(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
117
        try {
118
            if (testingMode)
119
                return this.getRepositoriesByCountryTesting(country, mode, includeUnknownCountries);
120
            LOGGER.debug("Getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
121

    
122
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
123
//            List<Repository> reposList = this.repoAPI.getRepositoriesPerCountry(mode).get(country);
124

    
125
            Boolean managed = null;
126
            List<Repository> reposList = repositoryApi.getRepositoriesByCountry(country,mode,managed);
127
            if (reposList == null) {
128
                retTuple.setFirst(new ArrayList<Repository>());
129
//                if (!includeUnknownCountries) {
130
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
131
//                }
132
            } else {
133
                retTuple.setFirst(reposList);
134
            }
135

    
136
            if (includeUnknownCountries) {
137
                List<Repository> withoutCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("Without Country");
138
                List<Repository> unknownCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("UNKNOWN");
139
                List<Repository> totalList = new ArrayList<Repository>();
140
                if (withoutCountryList != null)
141
                    totalList.addAll(withoutCountryList);
142
                if (unknownCountryList != null)
143
                    totalList.addAll(unknownCountryList);
144
                retTuple.setSecond(totalList);
145
            }
146

    
147
            return retTuple;
148

    
149
        } catch (Exception e) {
150
            LOGGER.error("Error while getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
151
            if (e instanceof RepositoryServiceException) {
152
                throw (RepositoryServiceException) e;
153
            } else {
154
                emailUtils.reportException(e);
155
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
156
            }
157
        }
158
    }
159

    
160
    @Override
161
    public List<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
162
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
163
    }
164

    
165
    @Override
166
    public DatasourcesCollection getRepositoriesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
167

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

    
181
/*
182
	if (includeShared) {
183
                //TODO create dao to save-get shared datasourcesIDs
184
                List<String> sharedDatasourceIds = new ArrayList<String>();
185
                retDatasources.setSharedDatasources(this.repoAPI.getReposByIds(sharedDatasourceIds));
186
                //geting Piwik Info
187
                for(Repository repository: retDatasources.getSharedDatasources())
188
                    repository.setPiwikInfo(this.getPiwikSiteForRepository(repository.getId()));
189
            }
190

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

    
206
    @Override
207
    public List<String> getRepositoryUrlsOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
208
        try {
209
            LOGGER.debug("Getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
210
            List<String> retRepos = new ArrayList<String>();
211

    
212
            int page = 0;
213
            String size = "50";
214
            List<String> resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
215
            while(resultSet.size() > 0 ){
216
                retRepos.addAll(resultSet);
217
                page++;
218
                resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
219
            }
220
            return retRepos;
221

    
222
        } catch (Exception e) {
223
            LOGGER.error("Error while getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
224
            emailUtils.reportException(e);
225
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
226
        }
227
    }
228

    
229
    @Override
230
    public Repository getRepository(String repoId) throws RepositoryServiceException {
231
        try {
232
            LOGGER.debug("Getting repository with id: " + repoId);
233
            Repository repo = repositoryApi.getRepositoryById(repoId);
234

    
235
            if (repo != null) {
236
                for (RepositoryInterface iFace : repo.getInterfaces()) {
237
                    if (!iFace.getContentDescription().equals("file::hybrid") && iFace.getAccessProtocol().equalsIgnoreCase("oai")) {
238
                        iFace.setComplianceName(getComplianceName(iFace.getCompliance()));
239
                        if (iFace.getCompliance().equals("notCompatible"))
240
                            iFace.setComplianceName("not compatible");
241
                    }
242
                }
243

    
244
                //geting Piwik Info
245
                repo.setPiwikInfo(this.getPiwikSiteForRepository(repoId));
246

    
247
            } else
248
                throw new RepositoryServiceException("registration.repositoryNotExists", RepositoryServiceException.ErrorCode.REPOSITORY_NOT_EXISTS);
249
            return repo;
250

    
251
        } catch (Exception e) {
252
            LOGGER.error("Error while getting repository with id: " + repoId, e);
253
            if (e instanceof RepositoryServiceException) {
254
                throw (RepositoryServiceException) e;
255
            } else {
256
                emailUtils.reportException(e);
257
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
258
            }
259
        }
260
    }
261

    
262
    @Override
263
    public Map<String, String> getCountries(Boolean existingOnly, String mode) throws RepositoryServiceException {
264
        try {
265
            LOGGER.debug("Getting countries");
266
            List<String> countries = new ArrayList<String>();
267

    
268
            Map<String, String> countriesMap = new TreeMap<String, String>();
269

    
270
            if (existingOnly) {
271
                LOGGER.debug("using the repositories map");
272
                countries.addAll(this.repoAPI.getRepositoriesByCountry(mode).keySet());
273
            } else {
274
                LOGGER.debug("using \"dnet:countries\" vocabulary");
275
                countries.addAll(this.getVocabulary("dnet:countries").getEnglishNames());
276
            }
277
//            countries.addAll(repositoryApi.getDnetCountries());
278
            for (String country : countries) {
279
                countriesMap.put(country, WordUtils.capitalizeFully(country));
280
            }
281

    
282
            return countriesMap;
283

    
284
        } catch (Exception e) {
285
            LOGGER.error("Error while getting getting countries", e);
286
            if (e instanceof RepositoryServiceException) {
287
                throw (RepositoryServiceException) e;
288
            } else {
289
                emailUtils.reportException(e);
290
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
291
            }
292
        }
293
    }
294

    
295
    @Override
296
    public Map<String, String> getCountries() throws RepositoryServiceException {
297
        return this.getCountries(false, null);
298
    }
299

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

    
312
    }
313

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

    
327
    @Override
328
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
329
        return repositoryApi.getDatasourceClasses(mode);
330
    }
331

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

    
337
    @Override
338
    public void storeRepository(Repository repo, String mode) throws RepositoryServiceException {
339

    
340
        try {
341
           /* LOGGER.debug("Storing repository with name: " + repo.getOfficialName());
342
            //List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
343
            JSONObject params = new JSONObject();
344
            params.put("datatype", mode);
345
            ObjectMapper mapper = new ObjectMapper();
346
            String json_repo = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repo);
347
            params.put("repository", json_repo);*/
348

    
349

    
350
            //repositoryApi.addRepository(params.toString());
351
            repositoryApi.addRepository(mode,repo);
352
            LOGGER.debug("Repository with name: " + repo.getOfficialName() + " stored!");
353

    
354
        }catch (Exception e) {
355
            emailUtils.reportException(e);
356
            LOGGER.error("Error while storing repository with name: " + repo.getOfficialName(), e);
357
            throw new RepositoryServiceException("Error while storing repository", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
358
        }
359
    }
360

    
361
    @Override
362
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
363
        try {
364
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
365

    
366
	    //TODO SOS, check old API
367

    
368
            //this.repoAPI.updateRepositoryInformation(repo);
369
            repositoryApi.updateEnglishName(repo.getId(),repo.getEnglishName());
370
            repositoryApi.updateLatitude(repo.getId(), String.valueOf(repo.getLatitude()));
371
            repositoryApi.updateLongitude(repo.getId(), String.valueOf(repo.getLongitude()));
372
            repositoryApi.updateOfficialName(repo.getId(),repo.getOfficialName());
373
            repositoryApi.updateLogoUrl(repo.getId(),repo.getLogoUrl());
374
            repositoryApi.updateTimezone(repo.getId(),String.valueOf(repo.getTimezone()));
375
            repositoryApi.updatePlatform(repo.getId(),repo.getTypology());
376

    
377
        } catch (Exception e) {
378
            LOGGER.error("Error while updating information of repo: " + repo.getOfficialName(), e);
379
            if (e instanceof RepositoryServiceException) {
380
                throw (RepositoryServiceException) e;
381
            } else {
382
                emailUtils.reportException(e);
383
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
384
            }
385
        }
386
    }
387

    
388
    @Override
389
    public RepositoryInterface updateInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
390
        try {
391
            LOGGER.debug("updating interface with id: " + iFace.getId());
392
            RepositoryInterface retIface = null;
393
            retIface = this.repoAPI.updateRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
394
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
395

    
396
            return retIface;
397
        } catch (Exception e) {
398
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
399
            if (e instanceof RepositoryServiceException) {
400
                throw (RepositoryServiceException) e;
401
            } else {
402
                emailUtils.reportException(e);
403
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
404
            }
405
        }
406
    }
407

    
408
    @Override
409
    public RepositoryInterface insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
410
        try {
411
            LOGGER.debug("inserting interface with id: " + iFace.getId());
412
            RepositoryInterface retIface = null;
413
            //retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
414

    
415
          /*  JSONObject params = new JSONObject();
416
            params.put("datatype",datatype);
417
            params.put("repoId",repoId);
418
            params.put("iFace",iFace);*/
419
            //retIface = repositoryApi.addRepositoryInterface(params.toString());
420

    
421
            retIface = repositoryApi.addRepositoryInterface(datatype,repoId,iFace);
422
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
423
            return retIface;
424

    
425
        } catch (Exception e) {
426
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
427
            if (e instanceof RepositoryServiceException) {
428
                throw (RepositoryServiceException) e;
429
            } else {
430
                emailUtils.reportException(e);
431
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
432
            }
433
        }
434
    }
435

    
436
    @Override
437
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
438
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
439
        iFaces.add(iFace);
440
        this.deleteInterfaces(repoId, iFaces, datatype);
441
    }
442

    
443
    @Override
444
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
445
        try {
446
            LOGGER.debug("deleting interfaces of repo: " + repoId);
447
            //this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
448

    
449
            for(RepositoryInterface iFace : iFaces) {
450
                LOGGER.info("deleting repository interface with url/set/id: " + iFace.getBaseUrl() + "/"
451
                        + iFace.getAccessSet() + "/" + iFace.getId());
452
                repositoryApi.deleteRepositoryInterface(iFace.getId());
453
            }
454

    
455
        } catch (Exception e) {
456
            LOGGER.error("deleting interfaces of repo: " + repoId, e);
457
            if (e instanceof RepositoryServiceException) {
458
                throw (RepositoryServiceException) e;
459
            } else {
460
                emailUtils.reportException(e);
461
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
462
            }
463
        }
464

    
465
    }
466

    
467
    @Override
468
    public DatasourceVocabularies getDatasourceVocabularies(String mode) throws RepositoryServiceException {
469
        try {
470
            LOGGER.debug("Getting vocabularies for datasource with type: " + mode);
471
            DatasourceVocabularies vocs = new DatasourceVocabularies();
472
            vocs.setCountries(this.getCountries());
473
            vocs.setDatasourceClasses(this.getDatasourceClasses(mode));
474
            vocs.setTimezones(this.getTimezones());
475
            vocs.setTypologies(this.getTypologies());
476
            vocs.setCompatibilityLevels(this.getCompatibilityClasses(mode));
477

    
478
            return vocs;
479

    
480
        } catch (Exception e) {
481
            LOGGER.error("Error while getting vocabularies for datasource with type: \" + mode", e);
482
            emailUtils.reportException(e);
483
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
484
        }
485
    }
486

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

    
491
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
492
            List<Repository> reposList = new ArrayList<Repository>();
493
            reposList.add(this.repoAPI.getRepository("opendoar____::1356"));
494
            reposList.add(this.repoAPI.getRepository("opendoar____::2678"));
495
            reposList.add(this.repoAPI.getRepository("opendoar____::2980"));
496
            reposList.add(this.repoAPI.getRepository("opendoar____::1347"));
497
            reposList.add(this.repoAPI.getRepository("opendoar____::2984"));
498

    
499
            retTuple.setFirst(reposList);
500

    
501
            if (includeUnknownCountries) {
502
                List<Repository> totalList = new ArrayList<Repository>();
503
                totalList.add(this.repoAPI.getRepository("opendoar____::3000"));
504
                totalList.add(this.repoAPI.getRepository("opendoar____::1027"));
505
                totalList.add(this.repoAPI.getRepository("opendoar____::1096"));
506

    
507
                retTuple.setSecond(totalList);
508
            }
509

    
510
            return retTuple;
511

    
512
        } catch (Exception e) {
513
            LOGGER.error("Error while getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
514
            if (e instanceof RepositoryServiceException) {
515
                throw (RepositoryServiceException) e;
516
            } else {
517
                emailUtils.reportException(e);
518
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
519
            }
520
        }
521
    }
522

    
523
    @Override
524
    public String getLatestUpdateDateOfList(String mode) throws RepositoryServiceException {
525
        try {
526
            LOGGER.debug("Getting latest update date of list: " + mode);
527
            return this.repoAPI.getListLatestUpdate(mode).split("T")[0];
528

    
529
        } catch (Exception e) {
530
            LOGGER.error("Error while getting latest update date of list: " + mode, e);
531
            emailUtils.reportException(e);
532
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
533
        }
534
    }
535

    
536
    @Override
537
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
538
        try {
539
            LOGGER.debug("Repo id -> " + repoId);
540
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
541
        } catch (EmptyResultDataAccessException e) {
542
            return null;
543
        }
544
    }
545

    
546
    @Override
547
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
548
        
549
        try {
550
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(repository.getOfficialName(), "UTF-8") + "&url=" + URLEncoder.encode(repository.getWebsiteUrl(), "UTF-8");
551
            Map<String, Object> map = new ObjectMapper().readValue(new URL(URL), Map.class);
552

    
553
            String siteId = null;
554
            if(map.get("value")!=null) {
555
                siteId = map.get("value").toString();
556
            }
557

    
558
            String authenticationToken = "32846584f571be9b57488bf4088f30ea";
559

    
560
            PiwikInfo piwikInfo = new PiwikInfo();
561
            piwikInfo.setRepositoryId(repository.getId());
562
            piwikInfo.setRepositoryName(repository.getOfficialName());
563
            piwikInfo.setCountry(repository.getCountryName());
564
            piwikInfo.setSiteId(siteId);
565
            piwikInfo.setAuthenticationToken(authenticationToken);
566
            piwikInfo.setRequestorEmail(requestor.getEmail());
567
            piwikInfo.setRequestorName(requestor.getFirstname() + " " + requestor.getLastname());
568
            piwikInfo.setValidated(false);
569

    
570
            this.piwikDAO.savePiwikInfo(piwikInfo);
571

    
572
            emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
573
            emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
574

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

    
589
    @Override
590
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
591
        try {
592
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
593

    
594
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
595
            return piwikScript;
596

    
597
        } catch (EmptyResultDataAccessException e) {
598
            return null;
599
        }
600
    }
601

    
602
    @Override
603
    public List<PiwikInfo> getPiwikSitesForRepositories() throws RepositoryServiceException {
604
        try {
605

    
606
            List<PiwikInfo> piwikInfos = new ArrayList<>();
607
            piwikInfos = this.piwikDAO.getPiwikSitesForRepos();
608

    
609
            return piwikInfos;
610

    
611
        } catch (EmptyResultDataAccessException e) {
612
            LOGGER.error("Error while getting list of piwik sites: ", e);
613
            emailUtils.reportException(e);
614
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
615
        }
616
    }
617

    
618
    @Override
619
    public void markPiwikSiteAsValidated(String repositoryId) throws RepositoryServiceException {
620
        try {
621
            this.piwikDAO.markPiwikSiteAsValidated(repositoryId);
622

    
623
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repositoryId);
624
            emailUtils.sendAdministratorMetricsEnabled(piwikInfo);
625
            emailUtils.sendUserMetricsEnabled(piwikInfo);
626

    
627
        } catch (EmptyResultDataAccessException e) {
628
            LOGGER.error("Error while approving piwik site: ", e);
629
            emailUtils.reportException(e);
630
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
631
        } catch (Exception e) {
632
            LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e);
633
            emailUtils.reportException(e);
634
        }
635
    }
636

    
637
    @Override
638
    public MetricsInfo getMetricsInfoForRepository(String repoId) throws RepositoryServiceException {
639
        try {
640

    
641
            MetricsInfo metricsInfo = new MetricsInfo();
642
            metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
643
            metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
644
            return metricsInfo;
645

    
646
        } catch (Exception e) {
647
            LOGGER.error("Error while getting metrics info for repository: ", e);
648
            emailUtils.reportException(e);
649
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
650
        }
651
    }
652

    
653
    private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
654

    
655
        //build the uri params
656
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
657

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

    
674
        return resp.getBody();
675
    }
676

    
677
    private String getCountryCode(String countryName) {
678
        Vocabulary countries = this.getVocabulary("dnet:countries");
679

    
680
        return countries.getEncoding(countryName);
681
    }
682

    
683
    private String getDatasourceClassCode(String datasourceClassName) {
684
        Vocabulary datasourceClasses = this.getVocabulary("dnet:datasource_typologies");
685

    
686
        return datasourceClasses.getEncoding(datasourceClassName);
687
    }
688

    
689
    private String getComplianceName(String complianceCode) {
690
        Vocabulary compatibilityLevels = this.getVocabulary("dnet:compatibilityLevel");
691

    
692
        return compatibilityLevels.getEnglishName(complianceCode);
693
    }
694

    
695
    private Vocabulary getVocabulary(String vocName) {
696

    
697
        if (!vocabularyMap.containsKey(vocName)) {
698
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
699
        }
700
        return vocabularyMap.get(vocName);
701
    }
702

    
703
    @Scheduled(fixedRate = 3600000)
704
    private void loadVocabularies() {
705
        LOGGER.debug("loading vocabularies");
706
        for (String vocName : vocabularyNames) {
707
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
708
        }
709
    }
710

    
711
    private String getOpenAIREId(String repoId) {
712

    
713
        if (repoId != null && repoId.contains("::")) {
714
            return repoId.split("::")[0] + "::" + DigestUtils.md5Hex(repoId.split("::")[1]);
715
        }
716

    
717
        return null;
718
    }
719

    
720
    @Override
721
    public Aggregations getRepositoryAggregations(String repoId) throws JSONException {
722
        return repositoryApi.getRepositoryAggregations(repoId);
723
    }
724
}
(4-4/6)