Project

General

Profile

1
package eu.dnetlib.repo.manager.service.controllers;
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.PostAuthorize;
17
import org.springframework.security.access.prepost.PreAuthorize;
18
import org.springframework.stereotype.Component;
19
import org.springframework.web.bind.annotation.PathVariable;
20
import org.springframework.web.bind.annotation.RequestBody;
21
import org.springframework.web.bind.annotation.RequestParam;
22

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

    
32
@Component
33
public class PiWikApiImpl implements PiWikApi{
34

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

    
39

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

    
43

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

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

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

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

    
55
    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";
56

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

    
59

    
60

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

    
65

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

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

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

    
94
    }
95

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

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

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

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

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

    
131
    @Override
132
    @PreAuthorize("hasRole('ROLE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
133
    public PiwikInfo enableMetricsForRepository(@RequestParam("officialName") String officialName,
134
                                                @RequestParam("repoWebsite") String repoWebsite,
135
                                                @RequestBody PiwikInfo piwikInfo) throws RepositoryServiceException {
136

    
137
        try {
138

    
139
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(officialName, "UTF-8") + "&url="
140
                    + URLEncoder.encode(repoWebsite, "UTF-8");
141
            Map map = new ObjectMapper().readValue(new URL(URL), Map.class);
142
            String siteId = null;
143
            if(map.get("value")!=null) {
144
                siteId = map.get("value").toString();
145
            }
146
            piwikInfo.setSiteId(siteId);
147

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

    
166

    
167
}
(9-9/15)