Project

General

Profile

1
package eu.dnetlib.repo.manager.service;
2

    
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import eu.dnetlib.domain.data.PiwikInfo;
5
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
6
import org.apache.commons.codec.digest.DigestUtils;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.beans.factory.annotation.Qualifier;
10
import org.springframework.beans.factory.annotation.Value;
11
import org.springframework.dao.EmptyResultDataAccessException;
12
import org.springframework.http.HttpStatus;
13
import org.springframework.http.ResponseEntity;
14
import org.springframework.jdbc.core.JdbcTemplate;
15
import org.springframework.jdbc.core.RowMapper;
16
import org.springframework.security.access.prepost.PreAuthorize;
17
import org.springframework.stereotype.Service;
18
import org.springframework.web.bind.annotation.PathVariable;
19
import org.springframework.web.bind.annotation.RequestBody;
20
import org.springframework.web.bind.annotation.RequestParam;
21

    
22
import javax.sql.DataSource;
23
import java.io.IOException;
24
import java.io.UnsupportedEncodingException;
25
import java.net.URL;
26
import java.net.URLEncoder;
27
import java.sql.Types;
28
import java.util.List;
29
import java.util.Map;
30

    
31
@Service("piwikService")
32
public class PiWikApiImpl implements PiWikApi {
33

    
34
    @Qualifier("repomanager.dataSource")
35
    @Autowired
36
    private DataSource dataSource;
37

    
38

    
39
    @Value("${services.repomanager.analyticsURL}")
40
    private String analyticsURL;
41

    
42

    
43
    @Autowired
44
    @Qualifier("emailUtils")
45
    EmailUtils emailUtils;
46

    
47
    private static final Logger LOGGER = Logger
48
            .getLogger(PiWikApiImpl.class);
49

    
50
    private final static String GET_PIWIK_SITE = "select repositoryid, siteid, authenticationtoken, creationdate, requestorname, requestoremail, validated, validationdate, comment, repositoryname, country from piwik_site where repositoryid = ?;";
51

    
52
    private final static String INSERT_PIWIK_INFO = "insert into piwik_site (repositoryid, siteid, creationdate, requestorname, requestoremail, validated, repositoryname, country, authenticationtoken) values (?, ?, now(), ?, ?, ?, ?, ?, ?)";
53

    
54
    private final static String GET_PIWIK_SITES = "select repositoryid, siteid, authenticationtoken, creationdate, requestorname, requestoremail, validated, validationdate, comment, repositoryname, country from piwik_site order by repositoryname";
55

    
56
    private final static String APPROVE_PIWIK_SITE = "update piwik_site set validated=true, validationdate=now() where repositoryid = ?;";
57

    
58

    
59

    
60
    private RowMapper<PiwikInfo> piwikRowMapper = (rs, i) -> new PiwikInfo(rs.getString("repositoryid"), getOpenaireId(rs.getString("repositoryid")), rs.getString("repositoryname"), rs.getString("country"),
61
            rs.getString("siteid"), rs.getString("authenticationtoken"), rs.getTimestamp("creationdate"), rs.getString("requestorname"), rs.getString("requestoremail"),
62
            rs.getBoolean("validated"), rs.getTimestamp("validationdate"), rs.getString("comment"));
63

    
64

    
65
    @Override
66
    public PiwikInfo getPiwikSiteForRepo(@PathVariable("repositoryId") String repositoryId) {
67
        try{
68
            return new JdbcTemplate(dataSource).queryForObject(GET_PIWIK_SITE, new String[]{repositoryId}, new int[]{Types.VARCHAR}, piwikRowMapper);
69
        }catch (EmptyResultDataAccessException e){
70
            return null;
71
        }
72
    }
73

    
74
    @Override
75
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PORTAL_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
76
    public PiwikInfo savePiwikInfo(@RequestBody PiwikInfo piwikInfo) {
77
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
78
        jdbcTemplate.update(INSERT_PIWIK_INFO, new Object[]{piwikInfo.getRepositoryId(), piwikInfo.getSiteId(), piwikInfo.getRequestorName(),
79
                        piwikInfo.getRequestorEmail(), piwikInfo.isValidated(), piwikInfo.getRepositoryName(), piwikInfo.getCountry(), piwikInfo.getAuthenticationToken()},
80
                new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
81
        return piwikInfo;
82
    }
83

    
84
    @Override
85
    public List<PiwikInfo> getPiwikSitesForRepos() {
86
        LOGGER.debug("Getting piwik sites for repos! ");
87
        try{
88
            return new JdbcTemplate(dataSource).query(GET_PIWIK_SITES, piwikRowMapper);
89
        }catch (EmptyResultDataAccessException e){
90
            return null;
91
        }
92

    
93
    }
94

    
95
    @Override
96
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PORTAL_ADMIN')")
97
    public ResponseEntity<Object> approvePiwikSite(@PathVariable("repositoryId") String repositoryId) {
98
        new JdbcTemplate(dataSource).update(APPROVE_PIWIK_SITE, new Object[] {repositoryId}, new int[] {Types.VARCHAR});
99
        return new ResponseEntity<>("OK",HttpStatus.OK);
100
    }
101

    
102
    @Override
103
    public String getOpenaireId(@PathVariable("repositoryId") String repositoryId) {
104
        if (repositoryId != null && repositoryId.contains("::"))
105
            return repositoryId.split("::")[0] + "::" + DigestUtils.md5Hex(repositoryId.split("::")[1]);
106
        return null;
107
    }
108

    
109
    @Override
110
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PORTAL_ADMIN')")
111
    public ResponseEntity<Object> markPiwikSiteAsValidated(@PathVariable("repositoryId") String repositoryId) throws RepositoryServiceException {
112
        try {
113
            approvePiwikSite(repositoryId);
114

    
115
            PiwikInfo piwikInfo = getPiwikSiteForRepo(repositoryId);
116
            emailUtils.sendAdministratorMetricsEnabled(piwikInfo);
117
            emailUtils.sendUserMetricsEnabled(piwikInfo);
118

    
119
        } catch (EmptyResultDataAccessException e) {
120
            LOGGER.error("Error while approving piwik site: ", e);
121
            emailUtils.reportException(e);
122
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
123
        } catch (Exception e) {
124
            LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e);
125
            emailUtils.reportException(e);
126
        }
127
        return new ResponseEntity<>("OK",HttpStatus.OK);
128
    }
129

    
130
    @Override
131
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PORTAL_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
132
    public PiwikInfo enableMetricsForRepository(@RequestParam("officialName") String officialName,
133
                                                @RequestParam("repoWebsite") String repoWebsite,
134
                                                @RequestBody PiwikInfo piwikInfo) throws RepositoryServiceException {
135
        try {
136
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(officialName, "UTF-8") + "&url="
137
                    + URLEncoder.encode(repoWebsite, "UTF-8");
138
            Map map = new ObjectMapper().readValue(new URL(URL), Map.class);
139
            String siteId = null;
140
            if(map.get("value")!=null) {
141
                siteId = map.get("value").toString();
142
            }
143
            piwikInfo.setSiteId(siteId);
144

    
145
            savePiwikInfo(piwikInfo);
146
            emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
147
            emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
148
        } catch (UnsupportedEncodingException uee) {
149
            LOGGER.error("Error while creating piwikScript URL", uee);
150
            emailUtils.reportException(uee);
151
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
152
        } catch (IOException ioe) {
153
            LOGGER.error("Error while creating piwik site", ioe);
154
            emailUtils.reportException(ioe);
155
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
156
        } catch (Exception e) {
157
            LOGGER.error("Error while sending email to administrator or user about the request to enable metrics", e);
158
            emailUtils.reportException(e);
159
        }
160
        return piwikInfo;
161
    }
162

    
163

    
164
}
(9-9/19)