Project

General

Profile

1 49868 panagiotis
package eu.dnetlib.repo.manager.service.controllers;
2
3 51525 panagiotis
import com.fasterxml.jackson.databind.ObjectMapper;
4 49878 antonis.le
import eu.dnetlib.domain.data.PiwikInfo;
5 51525 panagiotis
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
6 50945 panagiotis
import org.apache.commons.codec.digest.DigestUtils;
7 52781 panagiotis
import org.apache.log4j.Logger;
8 49868 panagiotis
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.beans.factory.annotation.Qualifier;
10 51525 panagiotis
import org.springframework.beans.factory.annotation.Value;
11 50219 panagiotis
import org.springframework.dao.EmptyResultDataAccessException;
12 52781 panagiotis
import org.springframework.http.HttpStatus;
13
import org.springframework.http.ResponseEntity;
14 49868 panagiotis
import org.springframework.jdbc.core.JdbcTemplate;
15
import org.springframework.jdbc.core.RowMapper;
16 52781 panagiotis
import org.springframework.security.access.prepost.PostAuthorize;
17 51656 panagiotis
import org.springframework.security.access.prepost.PreAuthorize;
18 49868 panagiotis
import org.springframework.stereotype.Component;
19
import org.springframework.web.bind.annotation.PathVariable;
20 50860 panagiotis
import org.springframework.web.bind.annotation.RequestBody;
21 51656 panagiotis
import org.springframework.web.bind.annotation.RequestParam;
22 49868 panagiotis
23
import javax.sql.DataSource;
24 51525 panagiotis
import java.io.IOException;
25
import java.io.UnsupportedEncodingException;
26
import java.net.URL;
27
import java.net.URLEncoder;
28 49868 panagiotis
import java.sql.Types;
29
import java.util.List;
30 51525 panagiotis
import java.util.Map;
31 49868 panagiotis
32
@Component
33 49898 panagiotis
public class PiWikApiImpl implements PiWikApi{
34 49868 panagiotis
35 52781 panagiotis
    @Qualifier("repomanager.dataSource")
36 49868 panagiotis
    @Autowired
37
    private DataSource dataSource;
38
39 51525 panagiotis
40
    @Value("${services.repomanager.analyticsURL}")
41
    private String analyticsURL;
42
43
44
    @Autowired
45
    @Qualifier("emailUtils")
46
    EmailUtils emailUtils;
47
48 52781 panagiotis
    private static final Logger LOGGER = Logger
49 49898 panagiotis
            .getLogger(PiWikApiImpl.class);
50 49868 panagiotis
51 49898 panagiotis
    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 49868 panagiotis
53 49898 panagiotis
    private final static String INSERT_PIWIK_INFO = "insert into piwik_site (repositoryid, siteid, creationdate, requestorname, requestoremail, validated, repositoryname, country, authenticationtoken) values (?, ?, now(), ?, ?, ?, ?, ?, ?)";
54 49868 panagiotis
55 49898 panagiotis
    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 49868 panagiotis
57 49931 panagiotis
    private final static String APPROVE_PIWIK_SITE = "update piwik_site set validated=true, validationdate=now() where repositoryid = ?;";
58 49868 panagiotis
59
60 51525 panagiotis
61 49898 panagiotis
    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 49868 panagiotis
65 49898 panagiotis
66 49868 panagiotis
    @Override
67
    public PiwikInfo getPiwikSiteForRepo(@PathVariable("repositoryId") String repositoryId) {
68 50219 panagiotis
        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 49868 panagiotis
    }
74
75
    @Override
76 53003 panagiotis
    @PreAuthorize("hasRole('ROLE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
77 50860 panagiotis
    public PiwikInfo savePiwikInfo(@RequestBody PiwikInfo piwikInfo) {
78 49868 panagiotis
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
79
        jdbcTemplate.update(INSERT_PIWIK_INFO, new Object[]{piwikInfo.getRepositoryId(), piwikInfo.getSiteId(), piwikInfo.getRequestorName(),
80 49878 antonis.le
                        piwikInfo.getRequestorEmail(), piwikInfo.isValidated(), piwikInfo.getRepositoryName(), piwikInfo.getCountry(), piwikInfo.getAuthenticationToken()},
81 49868 panagiotis
                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 49898 panagiotis
        LOGGER.debug("Getting piwik sites for repos! ");
88 50219 panagiotis
        try{
89
            return new JdbcTemplate(dataSource).query(GET_PIWIK_SITES, piwikRowMapper);
90
        }catch (EmptyResultDataAccessException e){
91
            return null;
92
        }
93
94 49868 panagiotis
    }
95
96
    @Override
97 51656 panagiotis
    @PreAuthorize("hasRole('ROLE_ADMIN')")
98 52781 panagiotis
    public ResponseEntity<Object> approvePiwikSite(@PathVariable("repositoryId") String repositoryId) {
99 49868 panagiotis
        new JdbcTemplate(dataSource).update(APPROVE_PIWIK_SITE, new Object[] {repositoryId}, new int[] {Types.VARCHAR});
100 52781 panagiotis
        return new ResponseEntity<>("OK",HttpStatus.OK);
101 49868 panagiotis
    }
102
103
    @Override
104 50845 panagiotis
    public String getOpenaireId(@PathVariable("repositoryId") String repositoryId) {
105 50945 panagiotis
        if (repositoryId != null && repositoryId.contains("::"))
106
            return repositoryId.split("::")[0] + "::" + DigestUtils.md5Hex(repositoryId.split("::")[1]);
107 49868 panagiotis
        return null;
108
    }
109
110 51525 panagiotis
    @Override
111 51656 panagiotis
    @PreAuthorize("hasRole('ROLE_ADMIN')")
112 52781 panagiotis
    public ResponseEntity<Object> markPiwikSiteAsValidated(@PathVariable("repositoryId") String repositoryId) throws RepositoryServiceException {
113 51525 panagiotis
        try {
114
            approvePiwikSite(repositoryId);
115 49868 panagiotis
116 51525 panagiotis
            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 52781 panagiotis
        return new ResponseEntity<>("OK",HttpStatus.OK);
129 51525 panagiotis
    }
130
131
    @Override
132 52781 panagiotis
    @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 51525 panagiotis
137
        try {
138 51656 panagiotis
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 51525 panagiotis
            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 52781 panagiotis
        return piwikInfo;
164 51525 panagiotis
    }
165
166
167 49868 panagiotis
}