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.Repository;
8
import eu.dnetlib.domain.data.RepositoryInterface;
9
import eu.dnetlib.domain.enabling.Vocabulary;
10
import eu.dnetlib.domain.functionality.UserProfile;
11
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
12
import eu.dnetlib.repo.manager.client.services.RepositoryService;
13
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
14
import eu.dnetlib.repo.manager.server.utils.LocalVocabularies;
15
import eu.dnetlib.domain.data.PiwikInfo;
16
import eu.dnetlib.repo.manager.service.controllers.RepositoryApi;
17
import eu.dnetlib.repo.manager.shared.*;
18
import eu.dnetlib.repos.RepoApi;
19
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
20
import org.apache.commons.lang.StringEscapeUtils;
21
import org.apache.commons.lang.WordUtils;
22
import org.apache.log4j.Logger;
23
import org.json.JSONException;
24
import org.json.JSONObject;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.beans.factory.annotation.Value;
27
import org.springframework.dao.EmptyResultDataAccessException;
28
import org.springframework.scheduling.annotation.Scheduled;
29
import org.springframework.stereotype.Service;
30

    
31
import javax.annotation.PostConstruct;
32
import java.text.Normalizer;
33
import java.util.*;
34
import java.util.concurrent.ConcurrentHashMap;
35

    
36
/**
37
 * Created by nikonas on 12/8/15.
38
 */
39
@SuppressWarnings("serial")
40
@Service("repositoryService")
41
public class RepositoryServiceImpl extends SpringGwtRemoteServiceServlet implements RepositoryService {
42

    
43
    private static final Logger LOGGER = Logger
44
            .getLogger(RepositoryServiceImpl.class);
45

    
46
    @Autowired
47
    private RepoApi repoAPI;
48

    
49
    @Autowired
50
    private EmailUtils emailUtils;
51

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

    
54
    @Autowired
55
    private VocabularyLoader vocabularyLoader;
56

    
57
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
58

    
59
    @Value("${services.repo-manager.repository.testing.mode}")
60
    private boolean testingMode;
61

    
62
    @Autowired
63
    private PiwikDAO piwikDAO;
64

    
65
    @Value("${services.repomanager.analyticsURL}")
66
    private String analyticsURL;
67

    
68
    private static final String PIWIK_SCRIPT = StringEscapeUtils.escapeHtml("<!-- Piwik -->\n" +
69
            "<script type=\"text/javascript\">\n" +
70
            "\tvar _paq = _paq || [];\n" +
71
            "\t_paq.push(['enableLinkTracking']);\n" +
72
            "\t(function() {\n" +
73
            "\t\tvar u=\"//analytics.openaire.eu/\";\n" +
74
            "\t\t_paq.push(['setTrackerUrl', u+'piwik.php']);\n" +
75
            "\t\t_paq.push(['setSiteId', $$$]);\n" +
76
            "\t\t<% if(handle != null){%>\n" +
77
            "\t\t\t_paq.push(['setCustomVariable', 1, 'oaipmhID',\"oai:<%= baseUrl %>:<%=handle %>\", 'page']);\n" +
78
            "\t\t\t_paq.push(['trackPageView']);\n" +
79
            "\t\t<}>\n" +
80
            "\t\tvar d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n" +
81
            "\t\tg.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);\n" +
82
            "\t})();\n" +
83
            "</script>\n" +
84
            "<noscript>\n" +
85
            "\t<p>\n" +
86
            "\t\t<img src=\"//analytics.openaire.eu/piwik.php?idsite=47\" style=\"border:0;\" alt=\"\" />\n" +
87
            "\t</p>\n" +
88
            "</noscript>\n" +
89
            "<!— End Piwik Code —>");
90

    
91

    
92
    @Autowired
93
    private RepositoryApi repositoryApi;
94

    
95

    
96

    
97
    @PostConstruct
98
    public void init() {
99
        this.loadVocabularies();
100
    }
101

    
102
    @Override
103
    public Tuple<List<Repository>, List<Repository>> getRepositoriesByCountry(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
104
        try {
105
            if (testingMode)
106
                return this.getRepositoriesByCountryTesting(country, mode, includeUnknownCountries);
107
            LOGGER.debug("Getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
108

    
109
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
110
//            List<Repository> reposList = this.repoAPI.getRepositoriesPerCountry(mode).get(country);
111

    
112
            List<Repository> reposList = repositoryApi.getRepositoriesByCountry(country,mode);
113
            if (reposList == null) {
114
                retTuple.setFirst(new ArrayList<Repository>());
115
//                if (!includeUnknownCountries) {
116
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
117
//                }
118
            } else {
119
                retTuple.setFirst(reposList);
120
            }
121

    
122
            if (includeUnknownCountries) {
123
                List<Repository> withoutCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("Without Country");
124
                List<Repository> unknownCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("UNKNOWN");
125
                List<Repository> totalList = new ArrayList<Repository>();
126
                if (withoutCountryList != null)
127
                    totalList.addAll(withoutCountryList);
128
                if (unknownCountryList != null)
129
                    totalList.addAll(unknownCountryList);
130
                retTuple.setSecond(totalList);
131
            }
132

    
133
            return retTuple;
134

    
135
        } catch (Exception e) {
136
            LOGGER.error("Error while getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
137
            if (e instanceof RepositoryServiceException) {
138
                throw (RepositoryServiceException) e;
139
            } else {
140
                emailUtils.reportException(e);
141
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
142
            }
143
        }
144
    }
145

    
146
    @Override
147
    public List<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
148
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
149
    }
150

    
151
    @Override
152
    public DatasourcesCollection getRepositoriesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
153

    
154
        DatasourcesCollection retDatasources = new DatasourcesCollection();
155
        try {
156
            LOGGER.debug("Getting repositories of user: " + userEmail + " . IncludeShared: "
157
                    + includeShared + " . IncludeByOthers: " + includeByOthers);
158
            int page = 0;
159
            String size = "50";
160
            List<Repository> resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
161
            while(resultSet.size() > 0 ){
162
                retDatasources.getDatasourcesOfUser().addAll(resultSet);
163
                page++;
164
                resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
165
            }
166
        } catch (JSONException e) {
167
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
168
        }
169
        return retDatasources;
170
    }
171

    
172
    @Override
173
    public List<String> getRepositoryUrlsOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
174
        try {
175
            LOGGER.debug("Getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
176
            List<String> retRepos = new ArrayList<String>();
177

    
178
            int page = 0;
179
            String size = "50";
180
            List<String> resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
181
            while(resultSet.size() > 0 ){
182
                retRepos.addAll(resultSet);
183
                page++;
184
                resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
185
            }
186
            return retRepos;
187

    
188
        } catch (Exception e) {
189
            LOGGER.error("Error while getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
190
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
191
        }
192
    }
193

    
194
    @Override
195
    public Repository getRepository(String repoId) throws RepositoryServiceException {
196
        try {
197
            LOGGER.debug("Getting repository with id: " + repoId);
198
            Repository repo = repositoryApi.getRepositoryById(repoId);
199

    
200
            if (repo != null) {
201
                for (RepositoryInterface iFace : repo.getInterfaces()) {
202
                    if (!iFace.getContentDescription().equals("file::hybrid") && iFace.getAccessProtocol().equalsIgnoreCase("oai")) {
203
                        iFace.setComplianceName(getComplianceName(iFace.getCompliance()));
204
                        if (iFace.getCompliance().equals("notCompatible"))
205
                            iFace.setComplianceName("not compatible");
206
                    }
207
                }
208
            } else
209
                throw new RepositoryServiceException("registration.repositoryNotExists", RepositoryServiceException.ErrorCode.REPOSITORY_NOT_EXISTS);
210
            return repo;
211

    
212
        } catch (Exception e) {
213
            LOGGER.error("Error while getting repository with id: " + repoId, e);
214
            if (e instanceof RepositoryServiceException) {
215
                throw (RepositoryServiceException) e;
216
            } else {
217
                emailUtils.reportException(e);
218
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
219
            }
220
        }
221
    }
222

    
223
    @Override
224
    public Map<String, String> getCountries(Boolean existingOnly, String mode) throws RepositoryServiceException {
225
        try {
226
            LOGGER.debug("Getting countries");
227
            List<String> countries = new ArrayList<String>();
228

    
229
            Map<String, String> countriesMap = new TreeMap<String, String>();
230

    
231
            if (existingOnly) {
232
                LOGGER.debug("using the repositories map");
233
                countries.addAll(this.repoAPI.getRepositoriesByCountry(mode).keySet());
234
            } else {
235
                LOGGER.debug("using \"dnet:countries\" vocabulary");
236
                countries.addAll(this.getVocabulary("dnet:countries").getEnglishNames());
237
            }
238
//            countries.addAll(repositoryApi.getDnetCountries());
239
            for (String country : countries) {
240
                countriesMap.put(country, WordUtils.capitalizeFully(country));
241
            }
242

    
243
            return countriesMap;
244

    
245
        } catch (Exception e) {
246
            LOGGER.error("Error while getting getting countries", e);
247
            if (e instanceof RepositoryServiceException) {
248
                throw (RepositoryServiceException) e;
249
            } else {
250
              //  emailUtils.reportException(e);
251
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
252
            }
253
        }
254
    }
255

    
256
    @Override
257
    public Map<String, String> getCountries() throws RepositoryServiceException {
258
        return this.getCountries(false, null);
259
    }
260

    
261
    @Override
262
    public List<Timezone> getTimezones() throws RepositoryServiceException {
263
        try {
264
            LOGGER.debug("Getting timezones from file");
265
//            return repositoryApi.getTimezones();
266
            return LocalVocabularies.timezones;
267
        } catch (Exception e) {
268
            LOGGER.error("Error while getting timezones from file", e);
269
            emailUtils.reportException(e);
270
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
271
        }
272

    
273
    }
274

    
275
    @Override
276
    public List<String> getTypologies() throws RepositoryServiceException {
277
        try {
278
            LOGGER.debug("Getting typologies from file");
279
           // return repositoryApi.getTypologies();
280
            return LocalVocabularies.typologies;
281
        } catch (Exception e) {
282
            LOGGER.error("Error while getting typologies from file", e);
283
            emailUtils.reportException(e);
284
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
285
        }
286
    }
287

    
288
    @Override
289
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
290
        return repositoryApi.getDatasourceClasses(mode);
291
    }
292

    
293
    @Override
294
    public Map<String, String> getCompatibilityClasses(String mode) throws RepositoryServiceException {
295
        return repositoryApi.getCompatibilityClasses(mode);
296
    }
297

    
298
    @Override
299
    public void storeRepository(Repository repo, String mode) throws RepositoryServiceException {
300

    
301
        try {
302
            LOGGER.debug("Storing repository with name: " + repo.getOfficialName());
303
            //List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
304
            JSONObject params = new JSONObject();
305
            params.put("datatype", mode);
306
            ObjectMapper mapper = new ObjectMapper();
307
            String json_repo = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repo);
308
            params.put("repository", json_repo);
309
            repositoryApi.addRepository(params.toString());
310
            LOGGER.debug("Repository with name: " + repo.getOfficialName() + " stored!");
311
        }catch (Exception e) {
312
                LOGGER.error("Error while storing repository with name: " + repo.getOfficialName(), e);
313
                throw new RepositoryServiceException("Error while storing repository", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
314
            }
315
        }
316

    
317
    @Override
318
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
319
        try {
320
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
321
            //this.repoAPI.updateRepositoryInformation(repo);
322
            repositoryApi.updateEnglishName(repo.getId(),repo.getEnglishName());
323
            repositoryApi.updateLatitude(repo.getId(), String.valueOf(repo.getLatitude()));
324
            repositoryApi.updateLongitude(repo.getId(), String.valueOf(repo.getLongitude()));
325
            repositoryApi.updateOfficialName(repo.getId(),repo.getOfficialName());
326
            repositoryApi.updateLogoUrl(repo.getId(),repo.getLogoUrl());
327
            repositoryApi.updateTimezone(repo.getId(),String.valueOf(repo.getTimezone()));
328
            repositoryApi.updatePlatform(repo.getId(),repo.getTypology());
329

    
330
        } catch (Exception e) {
331
            LOGGER.error("Error while updating information of repo: " + repo.getOfficialName(), e);
332
            if (e instanceof RepositoryServiceException) {
333
                throw (RepositoryServiceException) e;
334
            } else {
335
                emailUtils.reportException(e);
336
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
337
            }
338
        }
339
    }
340

    
341
    @Override
342
    public RepositoryInterface updateInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
343
        try {
344
            LOGGER.debug("updating interface with id: " + iFace.getId());
345
            RepositoryInterface retIface = null;
346
            retIface = this.repoAPI.updateRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
347
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
348

    
349
            return retIface;
350
        } catch (Exception e) {
351
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
352
            if (e instanceof RepositoryServiceException) {
353
                throw (RepositoryServiceException) e;
354
            } else {
355
                emailUtils.reportException(e);
356
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
357
            }
358
        }
359
    }
360

    
361
    @Override
362
    public RepositoryInterface insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
363
        try {
364
            LOGGER.debug("inserting interface with id: " + iFace.getId());
365
            RepositoryInterface retIface = null;
366
            //retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
367

    
368
            JSONObject params = new JSONObject();
369
            params.put("datatype",datatype);
370
            params.put("repoId",repoId);
371
            params.put("iFace",iFace);
372
            retIface = repositoryApi.addRepositoryInterface(params.toString());
373
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
374
            return retIface;
375

    
376
        } catch (Exception e) {
377
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
378
            if (e instanceof RepositoryServiceException) {
379
                throw (RepositoryServiceException) e;
380
            } else {
381
                emailUtils.reportException(e);
382
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
383
            }
384
        }
385
    }
386

    
387
    @Override
388
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
389
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
390
        iFaces.add(iFace);
391
        this.deleteInterfaces(repoId, iFaces, datatype);
392
    }
393

    
394
    @Override
395
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
396
        try {
397
            LOGGER.debug("deleting interfaces of repo: " + repoId);
398
            //this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
399

    
400
            for(RepositoryInterface iFace : iFaces) {
401
                LOGGER.info("deleting repository interface with url/set/id: " + iFace.getBaseUrl() + "/"
402
                        + iFace.getAccessSet() + "/" + iFace.getId());
403
                repositoryApi.deleteRepositoryInterface(iFace.getId());
404
            }
405

    
406
        } catch (Exception e) {
407
            LOGGER.error("deleting interfaces of repo: " + repoId, e);
408
            if (e instanceof RepositoryServiceException) {
409
                throw (RepositoryServiceException) e;
410
            } else {
411
                emailUtils.reportException(e);
412
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
413
            }
414
        }
415

    
416
    }
417

    
418
    @Override
419
    public DatasourceVocabularies getDatasourceVocabularies(String mode) throws RepositoryServiceException {
420
        try {
421
            LOGGER.debug("Getting vocabularies for datasource with type: " + mode);
422
            DatasourceVocabularies vocs = new DatasourceVocabularies();
423
            vocs.setCountries(this.getCountries());
424
            vocs.setDatasourceClasses(this.getDatasourceClasses(mode));
425
            vocs.setTimezones(this.getTimezones());
426
            vocs.setTypologies(this.getTypologies());
427
            vocs.setCompatibilityLevels(this.getCompatibilityClasses(mode));
428

    
429
            return vocs;
430

    
431
        } catch (Exception e) {
432
            LOGGER.error("Error while getting vocabularies for datasource with type: \" + mode", e);
433
            emailUtils.reportException(e);
434
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
435
        }
436
    }
437

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

    
442
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
443
            List<Repository> reposList = new ArrayList<Repository>();
444
            reposList.add(this.repoAPI.getRepository("opendoar____::1356"));
445
            reposList.add(this.repoAPI.getRepository("opendoar____::2678"));
446
            reposList.add(this.repoAPI.getRepository("opendoar____::2980"));
447
            reposList.add(this.repoAPI.getRepository("opendoar____::1347"));
448
            reposList.add(this.repoAPI.getRepository("opendoar____::2984"));
449

    
450
            retTuple.setFirst(reposList);
451

    
452
            if (includeUnknownCountries) {
453
                List<Repository> totalList = new ArrayList<Repository>();
454
                totalList.add(this.repoAPI.getRepository("opendoar____::3000"));
455
                totalList.add(this.repoAPI.getRepository("opendoar____::1027"));
456
                totalList.add(this.repoAPI.getRepository("opendoar____::1096"));
457

    
458
                retTuple.setSecond(totalList);
459
            }
460

    
461
            return retTuple;
462

    
463
        } catch (Exception e) {
464
            LOGGER.error("Error while getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
465
            if (e instanceof RepositoryServiceException) {
466
                throw (RepositoryServiceException) e;
467
            } else {
468
                emailUtils.reportException(e);
469
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
470
            }
471
        }
472
    }
473

    
474
    @Override
475
    public String getLatestUpdateDateOfList(String mode) throws RepositoryServiceException {
476
        try {
477
            LOGGER.debug("Getting latest update date of list: " + mode);
478
            return this.repoAPI.getListLatestUpdate(mode).split("T")[0];
479

    
480
        } catch (Exception e) {
481
            LOGGER.error("Error while getting latest update date of list: " + mode, e);
482
            emailUtils.reportException(e);
483
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
484
        }
485
    }
486

    
487
    @Override
488
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
489
        try {
490
            LOGGER.debug("Repo id -> " + repoId);
491
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
492
        } catch (EmptyResultDataAccessException e) {
493
            return null;
494
        }
495
    }
496

    
497
    @Override
498
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
499

    
500
        String URL = analyticsURL + "siteName=" + repository.getOfficialName() + "&url=" + repository.getWebsiteUrl();
501

    
502
        //TODO uncomment when we can communitcate with the piwik (create site)
503
//        try {
504
//            Map<String, Object> map = new ObjectMapper().readValue(URL, Map.class);
505
//
506
//            String siteId = (String) map.get("value");
507

    
508
            String siteId = new Random(new Date().getTime()).nextInt(200) + "";
509
            String authenticationToken = new Random(new Date().getTime()).nextInt(1000000000) + "";
510

    
511
            PiwikInfo piwikInfo = new PiwikInfo();
512
            piwikInfo.setRepositoryId(repository.getId());
513
            piwikInfo.setRepositoryName(repository.getOfficialName());
514
            piwikInfo.setCountry(repository.getCountryName());
515
            piwikInfo.setSiteId(siteId);
516
            piwikInfo.setAuthenticationToken(authenticationToken);
517
            piwikInfo.setRequestorEmail(requestor.getEmail());
518
            piwikInfo.setRequestorName(requestor.getFirstname() + " " + requestor.getLastname());
519
            piwikInfo.setValidated(false);
520

    
521
            this.piwikDAO.savePiwikInfo(piwikInfo);
522

    
523
            //TODO send this in an email as well to the usage stats admin list
524

    
525
//        } catch (IOException e) {
526
//            LOGGER.error("Error while creating piwik site", e);
527
//            emailUtils.reportException(e);
528
//            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
529
//        }
530
    }
531

    
532
    @Override
533
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
534
        try {
535
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
536

    
537
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
538
            return piwikScript;
539

    
540
        } catch (EmptyResultDataAccessException e) {
541
            return null;
542
        }
543
    }
544

    
545
    @Override
546
    public List<PiwikInfo> getPiwikSitesForRepositories() throws RepositoryServiceException {
547
        try {
548

    
549
            List<PiwikInfo> piwikInfos = new ArrayList<>();
550
            piwikInfos = this.piwikDAO.getPiwikSitesForRepos();
551

    
552
            return piwikInfos;
553

    
554
        } catch (EmptyResultDataAccessException e) {
555
            LOGGER.error("Error while getting list of piwik sites: ", e);
556
            emailUtils.reportException(e);
557
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
558
        }
559
    }
560

    
561
    @Override
562
    public void approvePiwikSite(String repositoryId) throws RepositoryServiceException {
563
        try {
564

    
565
            this.piwikDAO.approvePiwikSite(repositoryId);
566

    
567
        } catch (EmptyResultDataAccessException e) {
568
            LOGGER.error("Error while approving piwik site: ", e);
569
            emailUtils.reportException(e);
570
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
571
        }
572
    }
573

    
574
    private String getCountryCode(String countryName) {
575
        Vocabulary countries = this.getVocabulary("dnet:countries");
576

    
577
        return countries.getEncoding(countryName);
578
    }
579

    
580
    private String getDatasourceClassCode(String datasourceClassName) {
581
        Vocabulary datasourceClasses = this.getVocabulary("dnet:datasource_typologies");
582

    
583
        return datasourceClasses.getEncoding(datasourceClassName);
584
    }
585

    
586
    private String getComplianceName(String complianceCode) {
587
        Vocabulary compatibilityLevels = this.getVocabulary("dnet:compatibilityLevel");
588

    
589
        return compatibilityLevels.getEnglishName(complianceCode);
590
    }
591

    
592
    private Vocabulary getVocabulary(String vocName) {
593

    
594
        if (!vocabularyMap.containsKey(vocName)) {
595
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
596
        }
597
        return vocabularyMap.get(vocName);
598
    }
599

    
600
    @Scheduled(fixedRate = 3600000)
601
    private void loadVocabularies() {
602
        LOGGER.debug("loading vocabularies");
603
        for (String vocName : vocabularyNames) {
604
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
605
        }
606
    }
607

    
608
}
(4-4/6)