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
            LOGGER.debug("Resultset size -> " + resultSet.size() );
180
            while(resultSet.size() > 0 ){
181
                LOGGER.debug("Resultset size -> " + resultSet.size() );
182
                retDatasources.getDatasourcesOfUser().addAll(resultSet);
183
                page++;
184
                resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
185
            }
186
        } catch (JSONException e) {
187
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
188
        }
189
        return retDatasources;
190
    }
191

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

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

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

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

    
221
           // Repository repo = this.repoAPI.getRepository(repoId);
222

    
223
            Repository repo = repositoryApi.getRepositoryById(repoId);
224

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

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

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

    
254
            Map<String, String> countriesMap = new TreeMap<String, String>();
255

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

    
268
            return countriesMap;
269

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

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

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

    
298
    }
299

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

    
313
    @Override
314
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
315
        try {
316
            LOGGER.debug("Getting datasource classes for mode: " + mode);
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
        try {
346
            LOGGER.debug("Getting compatibility classes for mode: " + mode);
347
            Map<String, String> retMap = new HashMap<String, String>();
348

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

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

    
369
            return retMap;
370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
507
    }
508

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

    
520
            return vocs;
521

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

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

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

    
541
            retTuple.setFirst(reposList);
542

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

    
549
                retTuple.setSecond(totalList);
550
            }
551

    
552
            return retTuple;
553

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

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

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

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

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

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

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

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

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

    
611
            this.piwikDAO.savePiwikInfo(piwikInfo);
612

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

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

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

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

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

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

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

    
642
            return piwikInfos;
643

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

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

    
655
            this.piwikDAO.approvePiwikSite(repositoryId);
656

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

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

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

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

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

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

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

    
682
    private Vocabulary getVocabulary(String vocName) {
683

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

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

    
698
}
(4-4/6)