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.domain.data.Repository;
|
6
|
import eu.dnetlib.repo.manager.domain.OrderByField;
|
7
|
import eu.dnetlib.repo.manager.domain.OrderByType;
|
8
|
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
|
9
|
import org.apache.commons.codec.digest.DigestUtils;
|
10
|
import org.apache.log4j.Logger;
|
11
|
import org.springframework.beans.factory.annotation.Autowired;
|
12
|
import org.springframework.beans.factory.annotation.Qualifier;
|
13
|
import org.springframework.beans.factory.annotation.Value;
|
14
|
import org.springframework.dao.EmptyResultDataAccessException;
|
15
|
import org.springframework.http.HttpStatus;
|
16
|
import org.springframework.http.ResponseEntity;
|
17
|
import org.springframework.jdbc.core.JdbcTemplate;
|
18
|
import org.springframework.jdbc.core.PreparedStatementSetter;
|
19
|
import org.springframework.jdbc.core.RowMapper;
|
20
|
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
21
|
import org.springframework.security.access.prepost.PreAuthorize;
|
22
|
import org.springframework.security.core.context.SecurityContextHolder;
|
23
|
import org.springframework.stereotype.Service;
|
24
|
import org.springframework.web.bind.annotation.PathVariable;
|
25
|
import org.springframework.web.bind.annotation.RequestBody;
|
26
|
import org.springframework.web.bind.annotation.RequestParam;
|
27
|
|
28
|
import javax.sql.DataSource;
|
29
|
import java.io.IOException;
|
30
|
import java.io.UnsupportedEncodingException;
|
31
|
import java.net.URL;
|
32
|
import java.net.URLEncoder;
|
33
|
import java.sql.PreparedStatement;
|
34
|
import java.sql.SQLException;
|
35
|
import java.sql.Types;
|
36
|
import java.util.Arrays;
|
37
|
import java.util.List;
|
38
|
import java.util.Map;
|
39
|
import java.util.stream.Collectors;
|
40
|
|
41
|
@Service("piwikService")
|
42
|
public class PiWikServiceImpl implements PiWikService {
|
43
|
|
44
|
@Qualifier("repomanager.dataSource")
|
45
|
@Autowired
|
46
|
private DataSource dataSource;
|
47
|
|
48
|
|
49
|
@Value("${services.repomanager.analyticsURL}")
|
50
|
private String analyticsURL;
|
51
|
|
52
|
|
53
|
@Autowired
|
54
|
private RepositoryService repositoryService;
|
55
|
|
56
|
@Autowired
|
57
|
@Qualifier("emailUtils")
|
58
|
private EmailUtils emailUtils;
|
59
|
|
60
|
private static final Logger LOGGER = Logger
|
61
|
.getLogger(PiWikServiceImpl.class);
|
62
|
|
63
|
private final static String GET_PIWIK_SITE = "select repositoryid, siteid, authenticationtoken, creationdate, requestorname, requestoremail, validated, validationdate, comment, repositoryname, country from piwik_site where repositoryid = ?;";
|
64
|
|
65
|
private final static String INSERT_PIWIK_INFO = "insert into piwik_site (repositoryid, siteid, creationdate, requestorname, requestoremail, validated, repositoryname, country, authenticationtoken) values (?, ?, now(), ?, ?, ?, ?, ?, ?)";
|
66
|
|
67
|
private final static String GET_PIWIK_SITES = "select count(*) OVER() as totals, repositoryid, siteid, authenticationtoken, creationdate, requestorname, requestoremail, validated, validationdate, comment, repositoryname, country from piwik_site ";
|
68
|
|
69
|
private final static String APPROVE_PIWIK_SITE = "update piwik_site set validated=true, validationdate=now() where repositoryid = ?;";
|
70
|
|
71
|
private RowMapper<PiwikInfo> piwikRowMapper = (rs, i) -> new PiwikInfo(rs.getString("repositoryid"), getOpenaireId(rs.getString("repositoryid")), rs.getString("repositoryname"), rs.getString("country"),
|
72
|
rs.getString("siteid"), rs.getString("authenticationtoken"), rs.getTimestamp("creationdate"), rs.getString("requestorname"), rs.getString("requestoremail"),
|
73
|
rs.getBoolean("validated"), rs.getTimestamp("validationdate"), rs.getString("comment"));
|
74
|
|
75
|
|
76
|
@Override
|
77
|
public PiwikInfo getPiwikSiteForRepo(String repositoryId) {
|
78
|
try{
|
79
|
return new JdbcTemplate(dataSource).queryForObject(GET_PIWIK_SITE, new String[]{repositoryId}, new int[]{Types.VARCHAR}, piwikRowMapper);
|
80
|
}catch (EmptyResultDataAccessException e){
|
81
|
return null;
|
82
|
}
|
83
|
}
|
84
|
|
85
|
@Override
|
86
|
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
|
87
|
public PiwikInfo savePiwikInfo(PiwikInfo piwikInfo) {
|
88
|
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
|
89
|
jdbcTemplate.update(INSERT_PIWIK_INFO, new Object[]{piwikInfo.getRepositoryId(), piwikInfo.getSiteId(), piwikInfo.getRequestorName(),
|
90
|
piwikInfo.getRequestorEmail(), piwikInfo.isValidated(), piwikInfo.getRepositoryName(), piwikInfo.getCountry(), piwikInfo.getAuthenticationToken()},
|
91
|
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
|
92
|
return piwikInfo;
|
93
|
}
|
94
|
|
95
|
@Override
|
96
|
public List<PiwikInfo> getPiwikSitesForRepos(OrderByField orderByField, OrderByType orderByType, int from, int quantity, String searchField) {
|
97
|
LOGGER.debug("Getting piwik sites for repos! ");
|
98
|
try{
|
99
|
String finalizedQuery = GET_PIWIK_SITES + " where ("+
|
100
|
" repositoryid ilike ? " +
|
101
|
" or siteid ilike ?" +
|
102
|
" or requestorname ilike ?" +
|
103
|
" or requestoremail ilike ?" +
|
104
|
" or comment ilike ?" +
|
105
|
" or repositoryname ilike ?"+
|
106
|
" or country ilike ?"
|
107
|
+") order by "+orderByField + " " + orderByType + " offset ? limit ?";
|
108
|
|
109
|
return new JdbcTemplate(dataSource).query(finalizedQuery, preparedStatement -> {
|
110
|
preparedStatement.setString(1,"%"+searchField+"%");
|
111
|
preparedStatement.setString(2,"%"+searchField+"%");
|
112
|
preparedStatement.setString(3,"%"+searchField+"%");
|
113
|
preparedStatement.setString(4,"%"+searchField+"%");
|
114
|
preparedStatement.setString(5,"%"+searchField+"%");
|
115
|
preparedStatement.setString(6,"%"+searchField+"%");
|
116
|
preparedStatement.setString(7,"%"+searchField+"%");
|
117
|
preparedStatement.setInt(8,from);
|
118
|
preparedStatement.setInt(9,quantity);
|
119
|
}, piwikRowMapper);
|
120
|
}catch (EmptyResultDataAccessException e){
|
121
|
return null;
|
122
|
}
|
123
|
|
124
|
}
|
125
|
|
126
|
@Override
|
127
|
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
|
128
|
public ResponseEntity<Object> approvePiwikSite(String repositoryId) {
|
129
|
new JdbcTemplate(dataSource).update(APPROVE_PIWIK_SITE, new Object[] {repositoryId}, new int[] {Types.VARCHAR});
|
130
|
return new ResponseEntity<>("OK",HttpStatus.OK);
|
131
|
}
|
132
|
|
133
|
@Override
|
134
|
public String getOpenaireId(String repositoryId) {
|
135
|
if (repositoryId != null && repositoryId.contains("::"))
|
136
|
return repositoryId.split("::")[0] + "::" + DigestUtils.md5Hex(repositoryId.split("::")[1]);
|
137
|
return null;
|
138
|
}
|
139
|
|
140
|
@Override
|
141
|
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
|
142
|
public ResponseEntity<Object> markPiwikSiteAsValidated(String repositoryId) throws RepositoryServiceException {
|
143
|
try {
|
144
|
approvePiwikSite(repositoryId);
|
145
|
|
146
|
PiwikInfo piwikInfo = getPiwikSiteForRepo(repositoryId);
|
147
|
emailUtils.sendAdministratorMetricsEnabled(piwikInfo);
|
148
|
emailUtils.sendUserMetricsEnabled(piwikInfo);
|
149
|
|
150
|
} catch (EmptyResultDataAccessException e) {
|
151
|
LOGGER.error("Error while approving piwik site: ", e);
|
152
|
emailUtils.reportException(e);
|
153
|
throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
|
154
|
} catch (Exception e) {
|
155
|
LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e);
|
156
|
emailUtils.reportException(e);
|
157
|
}
|
158
|
return new ResponseEntity<>("OK",HttpStatus.OK);
|
159
|
}
|
160
|
|
161
|
@Override
|
162
|
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
|
163
|
public PiwikInfo enableMetricsForRepository(String officialName,
|
164
|
String repoWebsite,
|
165
|
PiwikInfo piwikInfo) throws RepositoryServiceException {
|
166
|
try {
|
167
|
String URL = analyticsURL + "siteName=" + URLEncoder.encode(officialName, "UTF-8") + "&url="
|
168
|
+ URLEncoder.encode(repoWebsite, "UTF-8");
|
169
|
Map map = new ObjectMapper().readValue(new URL(URL), Map.class);
|
170
|
String siteId = null;
|
171
|
if(map.get("value")!=null) {
|
172
|
siteId = map.get("value").toString();
|
173
|
}
|
174
|
piwikInfo.setSiteId(siteId);
|
175
|
|
176
|
savePiwikInfo(piwikInfo);
|
177
|
|
178
|
Repository repository = repositoryService.getRepositoryById(piwikInfo.getRepositoryId());
|
179
|
repository.setPiwikInfo(piwikInfo);
|
180
|
|
181
|
repositoryService.updateRepository(repository, SecurityContextHolder.getContext().getAuthentication());
|
182
|
|
183
|
emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
|
184
|
emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
|
185
|
} catch (UnsupportedEncodingException uee) {
|
186
|
LOGGER.error("Error while creating piwikScript URL", uee);
|
187
|
emailUtils.reportException(uee);
|
188
|
throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
|
189
|
} catch (IOException ioe) {
|
190
|
LOGGER.error("Error while creating piwik site", ioe);
|
191
|
emailUtils.reportException(ioe);
|
192
|
throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
|
193
|
} catch (Exception e) {
|
194
|
LOGGER.error("Error while sending email to administrator or user about the request to enable metrics", e);
|
195
|
emailUtils.reportException(e);
|
196
|
}
|
197
|
return piwikInfo;
|
198
|
}
|
199
|
|
200
|
|
201
|
}
|