Project

General

Profile

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

    
3
import com.unboundid.util.Base64;
4
import eu.dnetlib.domain.data.Repository;
5
import eu.dnetlib.domain.data.RepositoryInterface;
6
import eu.dnetlib.domain.enabling.Vocabulary;
7
import eu.dnetlib.domain.functionality.UserProfile;
8
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
9
import eu.dnetlib.repo.manager.client.services.RepositoryService;
10
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
11
import eu.dnetlib.repo.manager.server.utils.LocalVocabularies;
12
import eu.dnetlib.repo.manager.service.controllers.RepositoryApi;
13
import eu.dnetlib.repo.manager.shared.*;
14
import eu.dnetlib.repos.RepoApi;
15
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
16
import org.apache.commons.lang.StringEscapeUtils;
17
import org.apache.commons.lang.WordUtils;
18
import org.apache.log4j.Logger;
19
import org.json.JSONException;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.beans.factory.annotation.Value;
22
import org.springframework.dao.EmptyResultDataAccessException;
23
import org.springframework.scheduling.annotation.Scheduled;
24
import org.springframework.stereotype.Service;
25

    
26
import javax.annotation.PostConstruct;
27
import java.text.Normalizer;
28
import java.util.*;
29
import java.util.concurrent.ConcurrentHashMap;
30

    
31
/**
32
 * Created by nikonas on 12/8/15.
33
 */
34
@SuppressWarnings("serial")
35
@Service("repositoryService")
36
public class RepositoryServiceImpl extends SpringGwtRemoteServiceServlet implements RepositoryService {
37

    
38
    private static final Logger LOGGER = Logger
39
            .getLogger(RepositoryServiceImpl.class);
40

    
41
    @Autowired
42
    private RepoApi repoAPI;
43

    
44
    @Autowired
45
    private EmailUtils emailUtils;
46

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

    
49
    @Autowired
50
    private VocabularyLoader vocabularyLoader;
51

    
52
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
53

    
54
    @Value("${services.repo-manager.repository.testing.mode}")
55
    private boolean testingMode;
56

    
57
    @Autowired
58
    private PiwikDAO piwikDAO;
59

    
60
    @Value("${services.repomanager.analyticsURL}")
61
    private String analyticsURL;
62

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

    
86

    
87
    /*----------------------------------------------------------------------------*/
88

    
89
    @Autowired
90
    private RepositoryApi repositoryApi;
91

    
92

    
93

    
94
    @PostConstruct
95
    public void init() {
96
        this.loadVocabularies();
97
    }
98

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

    
106
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
107
            List<Repository> reposList = this.repoAPI.getRepositoriesPerCountry(mode).get(country);
108
            if (reposList == null) {
109
                retTuple.setFirst(new ArrayList<Repository>());
110
//                if (!includeUnknownCountries) {
111
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
112
//                }
113
            } else {
114
                retTuple.setFirst(reposList);
115
            }
116

    
117
            if (includeUnknownCountries) {
118
                List<Repository> withoutCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("Without Country");
119
                List<Repository> unknownCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("UNKNOWN");
120
                List<Repository> totalList = new ArrayList<Repository>();
121
                if (withoutCountryList != null)
122
                    totalList.addAll(withoutCountryList);
123
                if (unknownCountryList != null)
124
                    totalList.addAll(unknownCountryList);
125
                retTuple.setSecond(totalList);
126
            }
127

    
128
            return retTuple;
129

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

    
141
    @Override
142
    public List<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
143
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
144
    }
145

    
146
    @Override
147
    public DatasourcesCollection getRepositoriesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
148
        /*try {
149
            LOGGER.debug("Getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
150
            DatasourcesCollection retDatasources = new DatasourcesCollection();
151
            retDatasources.setDatasourcesOfUser(this.repoAPI.getRepositoriesOfUser(userEmail, false));
152
            if (includeShared) {
153
                //TODO create dao to save-get shared datasourcesIDs
154
                List<String> sharedDatasourceIds = new ArrayList<String>();
155
                retDatasources.setSharedDatasources(this.repoAPI.getReposByIds(sharedDatasourceIds));
156
            }
157

    
158
            if (includeByOthers)
159
                retDatasources.setDatasourcesOfUser(this.repoAPI.getRepositoriesOfUser(userEmail, true));
160

    
161
            return retDatasources;
162

    
163
        } catch (Exception e) {
164
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
165
            if (e instanceof RepositoryServiceException) {
166
                throw (RepositoryServiceException) e;
167
            } else {
168
                emailUtils.reportException(e);
169
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
170
            }
171
        }*/
172
        DatasourcesCollection retDatasources = new DatasourcesCollection();
173
        try {
174
            LOGGER.debug("Getting repositories of user: " + userEmail + " . IncludeShared: "
175
                    + includeShared + " . IncludeByOthers: " + includeByOthers);
176
            int page = 1;
177
            String size = "10";
178
            List<Repository> resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
179
            while(resultSet.size() > 0 ){
180
                retDatasources.getDatasourcesOfUser().addAll(resultSet);
181
                page++;
182
                resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
183
            }
184
        } catch (JSONException e) {
185
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
186
        }
187
        return retDatasources;
188
    }
189

    
190
    @Override
191
    public List<String> getRepositoryUrlsOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
192
        try {
193
            LOGGER.debug("Getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
194
            List<String> retRepos = new ArrayList<String>();
195

    
196
            int page = 1;
197
            String size = "10";
198
            List<String> resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
199
            while(resultSet.size() > 0 ){
200
                retRepos.addAll(resultSet);
201
                page++;
202
                resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
203
            }
204
            //retRepos.addAll(this.repoAPI.getUrlsOfRepos(userEmail, false));
205
            return retRepos;
206

    
207
        } catch (Exception e) {
208
            LOGGER.error("Error while getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
209
            emailUtils.reportException(e);
210
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
211
        }
212
    }
213

    
214
    @Override
215
    public Repository getRepository(String repoId) throws RepositoryServiceException {
216
        try {
217
            LOGGER.debug("Getting repository with id: " + repoId);
218

    
219
           // Repository repo = this.repoAPI.getRepository(repoId);
220

    
221
            Repository repo = repositoryApi.getRepositoryById(repoId);
222

    
223
            if (repo != null) {
224
                for (RepositoryInterface iFace : repo.getInterfaces()) {
225
                    if (!iFace.getContentDescription().equals("file::hybrid") && iFace.getAccessProtocol().equalsIgnoreCase("oai")) {
226
                        iFace.setComplianceName(getComplianceName(iFace.getCompliance()));
227
                        if (iFace.getCompliance().equals("notCompatible"))
228
                            iFace.setComplianceName("not compatible");
229
                    }
230
                }
231
            } else
232
                throw new RepositoryServiceException("registration.repositoryNotExists", RepositoryServiceException.ErrorCode.REPOSITORY_NOT_EXISTS);
233
            return repo;
234

    
235
        } catch (Exception e) {
236
            LOGGER.error("Error while getting repository with id: " + repoId, e);
237
            if (e instanceof RepositoryServiceException) {
238
                throw (RepositoryServiceException) e;
239
            } else {
240
                emailUtils.reportException(e);
241
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
242
            }
243
        }
244
    }
245

    
246
    @Override
247
    public Map<String, String> getCountries(Boolean existingOnly, String mode) throws RepositoryServiceException {
248
        try {
249
            LOGGER.debug("Getting countries");
250
            List<String> countries = new ArrayList<String>();
251

    
252
            Map<String, String> countriesMap = new TreeMap<String, String>();
253

    
254
           /* if (existingOnly) {
255
                LOGGER.debug("using the repositories map");
256
                countries.addAll(this.repoAPI.getRepositoriesByCountry(mode).keySet());
257
            } else {
258
                LOGGER.debug("using \"dnet:countries\" vocabulary");
259
                countries.addAll(this.getVocabulary("dnet:countries").getEnglishNames());
260
            }*/
261
            countries.addAll(repositoryApi.getDnetCountries());
262
            for (String country : countries) {
263
                countriesMap.put(country, WordUtils.capitalizeFully(country));
264
            }
265

    
266
            return countriesMap;
267

    
268
        } catch (Exception e) {
269
            LOGGER.error("Error while getting getting countries", e);
270
            /*if (e instanceof RepositoryServiceException) {
271
                throw (RepositoryServiceException) e;
272
            } else {*/
273
              //  emailUtils.reportException(e);
274
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
275
           // }
276
        }
277
    }
278

    
279
    @Override
280
    public Map<String, String> getCountries() throws RepositoryServiceException {
281
        return this.getCountries(false, null);
282
    }
283

    
284
    @Override
285
    public List<Timezone> getTimezones() throws RepositoryServiceException {
286
        try {
287
            LOGGER.debug("Getting timezones from file");
288
            return repositoryApi.getTimezones();
289
            //return LocalVocabularies.timezones;
290
        } catch (Exception e) {
291
            LOGGER.error("Error while getting timezones from file", e);
292
            emailUtils.reportException(e);
293
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
294
        }
295

    
296
    }
297

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

    
311
    @Override
312
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
313
        return repositoryApi.getDatasourceClasses(mode);
314
       /* try {
315
            LOGGER.debug("Getting datasource classes for mode: " + mode);
316

    
317
            Map<String, String> retMap = new HashMap<String, String>();
318

    
319
            for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
320
                if (mode.equalsIgnoreCase("aggregator")) {
321
                    if (entry.getKey().contains("aggregator"))
322
                        retMap.put(entry.getKey(), entry.getValue());
323
                } else if (mode.equalsIgnoreCase("journal")) {
324
                    if (entry.getKey().contains("journal"))
325
                        retMap.put(entry.getKey(), entry.getValue());
326
                } else if (mode.equalsIgnoreCase("opendoar")) {
327
                    if (entry.getKey().contains("pubsrepository"))
328
                        retMap.put(entry.getKey(), entry.getValue());
329
                } else if (mode.equalsIgnoreCase("re3data")) {
330
                    if (entry.getKey().contains("datarepository"))
331
                        retMap.put(entry.getKey(), entry.getValue());
332
                }
333
            }
334
            return retMap;
335

    
336
        } catch (Exception e) {
337
            LOGGER.error("Error while getting datasource classes for mode: " + mode, e);
338
            emailUtils.reportException(e);
339
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
340
        }*/
341
    }
342

    
343
    @Override
344
    public Map<String, String> getCompatibilityClasses(String mode) throws RepositoryServiceException {
345
        return repositoryApi.getCompatibilityClasses(mode);
346
       /* try {
347
            LOGGER.debug("Getting compatibility classes for mode: " + mode);
348
            Map<String, String> retMap = new HashMap<String, String>();
349

    
350
            Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
351
            boolean foundData = false;
352
            for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
353
                if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
354
                    return compatibilityClasses;
355
                else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
356
                    if (entry.getKey().matches("^openaire[1-9].0_data$")) {
357
                        retMap.put(entry.getKey(), entry.getValue());
358
                        foundData = true;
359
                    }
360
                } else {
361
                    if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
362
                        retMap.put(entry.getKey(), entry.getValue());
363
                }
364
            }
365

    
366
            //TODO TO BE REMOVED WHEN VOCABULARIES ARE UPDATED
367
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA) && !foundData)
368
                retMap.put("openaire2.0_data", "OpenAIRE Data (funded, referenced datasets)");
369

    
370
            return retMap;
371

    
372
        } catch (Exception e) {
373
            LOGGER.error("Error while getting compatibility classes for mode: " + mode, e);
374
            emailUtils.reportException(e);
375
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
376
        }*/
377
    }
378

    
379
    @Override
380
    public void storeRepository(Repository repo, String mode) throws RepositoryServiceException {
381

    
382
        try {
383
            LOGGER.debug("Storing repository with name: " + repo.getOfficialName());
384

    
385
            List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
386

    
387
            //TODO update map
388
            repo.setCountryCode(getCountryCode(repo.getCountryName()));
389

    
390
            repo.setActivationId(UUID.randomUUID().toString());
391
//            repo.setRegisteredBy((String) session.get(LocalVocabularies.loggedInField));
392

    
393
            if (mode.equals("opendoar") || mode.equals("re3data")) {
394
                repo.setProvenanceActionClass("sysimport:crosswalk:entityregistry");
395
            } else if (mode.equals("journal")) {
396
                repo.setProvenanceActionClass("user:insert");
397
                repo.setCollectedFrom("infrastruct_::openaire");
398
                if (repo.getIssn() != null && repo.getIssn().length() == 0)
399
                    repo.setIssn(Base64.encode(repo.getOfficialName()).substring(0, 8));
400
                repo.setId("openaire____::issn" + repo.getIssn());
401
                repo.setNamespacePrefix("issn" + repo.getIssn());
402
            } else if (mode.equals("aggregator")) {
403
                repo.setProvenanceActionClass("user:insert");
404
                repo.setCollectedFrom("infrastruct_::openaire");
405
                repo.setId("openaire____::" + Base64.encode(repo.getOfficialName()));
406
                repo.setNamespacePrefix(Normalizer.normalize(repo.getOfficialName().toLowerCase().replace(" ", "_"), Normalizer.Form.NFD).replaceAll("[^a-zA-Z0-9]", ""));
407
                if (repo.getNamespacePrefix().length() > 12) {
408
                    repo.setNamespacePrefix(repo.getNamespacePrefix().substring(0, 12));
409
                } else {
410
                    while (repo.getNamespacePrefix().length() < 12)
411
                        repo.setNamespacePrefix(repo.getNamespacePrefix().concat("_"));
412
                }
413
            }
414

    
415
            this.repoAPI.storeRepository(repo, mode, interfacesToRegister);
416

    
417
        } catch (Exception e) {
418
            LOGGER.error("Error while Storing repository with name: " + repo.getOfficialName(), e);
419
            if (e instanceof RepositoryServiceException) {
420
                throw (RepositoryServiceException) e;
421
            } else {
422
                emailUtils.reportException(e);
423
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
424
            }
425
        }
426
    }
427

    
428
    @Override
429
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
430
        try {
431
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
432
            this.repoAPI.updateRepositoryInformation(repo);
433

    
434
        } catch (Exception e) {
435
            LOGGER.error("Error while updating information of repo: " + repo.getOfficialName(), e);
436
            if (e instanceof RepositoryServiceException) {
437
                throw (RepositoryServiceException) e;
438
            } else {
439
                emailUtils.reportException(e);
440
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
441
            }
442
        }
443
    }
444

    
445
    @Override
446
    public RepositoryInterface updateInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
447
        try {
448
            LOGGER.debug("updating interface with id: " + iFace.getId());
449
            RepositoryInterface retIface = null;
450
            retIface = this.repoAPI.updateRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
451
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
452

    
453
            return retIface;
454
        } catch (Exception e) {
455
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
456
            if (e instanceof RepositoryServiceException) {
457
                throw (RepositoryServiceException) e;
458
            } else {
459
                emailUtils.reportException(e);
460
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
461
            }
462
        }
463
    }
464

    
465
    @Override
466
    public RepositoryInterface insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
467
        try {
468
            LOGGER.debug("inserting interface with id: " + iFace.getId());
469
            RepositoryInterface retIface = null;
470
            retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
471
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
472
            return retIface;
473

    
474
        } catch (Exception e) {
475
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
476
            if (e instanceof RepositoryServiceException) {
477
                throw (RepositoryServiceException) e;
478
            } else {
479
                emailUtils.reportException(e);
480
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
481
            }
482
        }
483
    }
484

    
485
    @Override
486
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
487
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
488
        iFaces.add(iFace);
489
        this.deleteInterfaces(repoId, iFaces, datatype);
490
    }
491

    
492
    @Override
493
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
494
        try {
495
            LOGGER.debug("deleting interfaces of repo: " + repoId);
496
            this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
497

    
498
        } catch (Exception e) {
499
            LOGGER.error("deleting interfaces of repo: " + repoId, e);
500
            if (e instanceof RepositoryServiceException) {
501
                throw (RepositoryServiceException) e;
502
            } else {
503
                emailUtils.reportException(e);
504
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
505
            }
506
        }
507

    
508
    }
509

    
510
    @Override
511
    public DatasourceVocabularies getDatasourceVocabularies(String mode) throws RepositoryServiceException {
512
        try {
513
            LOGGER.debug("Getting vocabularies for datasource with type: " + mode);
514
            DatasourceVocabularies vocs = new DatasourceVocabularies();
515
            vocs.setCountries(this.getCountries());
516
            vocs.setDatasourceClasses(this.getDatasourceClasses(mode));
517
            vocs.setTimezones(this.getTimezones());
518
            vocs.setTypologies(this.getTypologies());
519
            vocs.setCompatibilityLevels(this.getCompatibilityClasses(mode));
520

    
521
            return vocs;
522

    
523
        } catch (Exception e) {
524
            LOGGER.error("Error while getting vocabularies for datasource with type: \" + mode", e);
525
            emailUtils.reportException(e);
526
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
527
        }
528
    }
529

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

    
534
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
535
            List<Repository> reposList = new ArrayList<Repository>();
536
            reposList.add(this.repoAPI.getRepository("opendoar____::1356"));
537
            reposList.add(this.repoAPI.getRepository("opendoar____::2678"));
538
            reposList.add(this.repoAPI.getRepository("opendoar____::2980"));
539
            reposList.add(this.repoAPI.getRepository("opendoar____::1347"));
540
            reposList.add(this.repoAPI.getRepository("opendoar____::2984"));
541

    
542
            retTuple.setFirst(reposList);
543

    
544
            if (includeUnknownCountries) {
545
                List<Repository> totalList = new ArrayList<Repository>();
546
                totalList.add(this.repoAPI.getRepository("opendoar____::3000"));
547
                totalList.add(this.repoAPI.getRepository("opendoar____::1027"));
548
                totalList.add(this.repoAPI.getRepository("opendoar____::1096"));
549

    
550
                retTuple.setSecond(totalList);
551
            }
552

    
553
            return retTuple;
554

    
555
        } catch (Exception e) {
556
            LOGGER.error("Error while getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
557
            if (e instanceof RepositoryServiceException) {
558
                throw (RepositoryServiceException) e;
559
            } else {
560
                emailUtils.reportException(e);
561
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
562
            }
563
        }
564
    }
565

    
566
    @Override
567
    public String getLatestUpdateDateOfList(String mode) throws RepositoryServiceException {
568
        try {
569
            LOGGER.debug("Getting latest update date of list: " + mode);
570
            return this.repoAPI.getListLatestUpdate(mode).split("T")[0];
571

    
572
        } catch (Exception e) {
573
            LOGGER.error("Error while getting latest update date of list: " + mode, e);
574
            emailUtils.reportException(e);
575
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
576
        }
577
    }
578

    
579
    @Override
580
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
581
        try {
582
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
583
        } catch (EmptyResultDataAccessException e) {
584
            return null;
585
        }
586
    }
587

    
588
    @Override
589
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
590

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

    
593
        //TODO uncomment when we can communitcate with the piwik (create site)
594
//        try {
595
//            Map<String, Object> map = new ObjectMapper().readValue(URL, Map.class);
596
//
597
//            String siteId = (String) map.get("value");
598

    
599
            String siteId = new Random(new Date().getTime()).nextInt(200) + "";
600
            String authenticationToken = new Random(new Date().getTime()).nextInt(1000000000) + "";
601

    
602
            PiwikInfo piwikInfo = new PiwikInfo();
603
            piwikInfo.setRepositoryId(repository.getId());
604
            piwikInfo.setRepositoryName(repository.getOfficialName());
605
            piwikInfo.setCountry(repository.getCountryName());
606
            piwikInfo.setSiteId(siteId);
607
            piwikInfo.setAuthenticationToken(authenticationToken);
608
            piwikInfo.setRequestorEmail(requestor.getEmail());
609
            piwikInfo.setRequestorName(requestor.getFirstname() + " " + requestor.getLastname());
610
            piwikInfo.setApproved(false);
611

    
612
            this.piwikDAO.savePiwikInfo(piwikInfo);
613

    
614
            //TODO send this in an email as well to the usage stats admin list
615

    
616
//        } catch (IOException e) {
617
//            LOGGER.error("Error while creating piwik site", e);
618
//            emailUtils.reportException(e);
619
//            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
620
//        }
621
    }
622

    
623
    @Override
624
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
625
        try {
626
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
627

    
628
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
629
            return piwikScript;
630

    
631
        } catch (EmptyResultDataAccessException e) {
632
            return null;
633
        }
634
    }
635

    
636
    @Override
637
    public List<PiwikInfo> getPiwikSitesForRepositories() throws RepositoryServiceException {
638
        try {
639

    
640
            List<PiwikInfo> piwikInfos = new ArrayList<>();
641
            piwikInfos = this.piwikDAO.getPiwikSitesForRepos();
642

    
643
            return piwikInfos;
644

    
645
        } catch (EmptyResultDataAccessException e) {
646
            LOGGER.error("Error while getting list of piwik sites: ", e);
647
            emailUtils.reportException(e);
648
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
649
        }
650
    }
651

    
652
    @Override
653
    public void approvePiwikSite(String repositoryId) throws RepositoryServiceException {
654
        try {
655

    
656
            this.piwikDAO.approvePiwikSite(repositoryId);
657

    
658
        } catch (EmptyResultDataAccessException e) {
659
            LOGGER.error("Error while approving piwik site: ", e);
660
            emailUtils.reportException(e);
661
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
662
        }
663
    }
664

    
665
    private String getCountryCode(String countryName) {
666
        Vocabulary countries = this.getVocabulary("dnet:countries");
667

    
668
        return countries.getEncoding(countryName);
669
    }
670

    
671
    private String getDatasourceClassCode(String datasourceClassName) {
672
        Vocabulary datasourceClasses = this.getVocabulary("dnet:datasource_typologies");
673

    
674
        return datasourceClasses.getEncoding(datasourceClassName);
675
    }
676

    
677
    private String getComplianceName(String complianceCode) {
678
        Vocabulary compatibilityLevels = this.getVocabulary("dnet:compatibilityLevel");
679

    
680
        return compatibilityLevels.getEnglishName(complianceCode);
681
    }
682

    
683
    private Vocabulary getVocabulary(String vocName) {
684

    
685
        if (!vocabularyMap.containsKey(vocName)) {
686
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
687
        }
688
        return vocabularyMap.get(vocName);
689
    }
690

    
691
    @Scheduled(fixedRate = 3600000)
692
    private void loadVocabularies() {
693
        LOGGER.debug("loading vocabularies");
694
        for (String vocName : vocabularyNames) {
695
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
696
        }
697
    }
698

    
699
}
(4-4/6)