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