1
|
package eu.dnetlib.datasource.publisher.clients;
|
2
|
|
3
|
import java.io.IOException;
|
4
|
import java.sql.Connection;
|
5
|
import java.sql.PreparedStatement;
|
6
|
import java.sql.ResultSet;
|
7
|
import java.sql.SQLException;
|
8
|
import java.util.List;
|
9
|
|
10
|
import com.google.common.collect.Lists;
|
11
|
import eu.dnetlib.datasource.publisher.ApiException;
|
12
|
import org.antlr.stringtemplate.StringTemplate;
|
13
|
import org.apache.commons.dbcp2.BasicDataSource;
|
14
|
import org.apache.commons.io.IOUtils;
|
15
|
import org.apache.commons.logging.Log;
|
16
|
import org.apache.commons.logging.LogFactory;
|
17
|
import org.springframework.beans.factory.annotation.Autowired;
|
18
|
import org.springframework.beans.factory.annotation.Value;
|
19
|
import org.springframework.core.io.ClassPathResource;
|
20
|
import org.springframework.core.io.Resource;
|
21
|
import org.springframework.http.HttpStatus;
|
22
|
|
23
|
/**
|
24
|
* Created by claudio on 25/11/2016.
|
25
|
*/
|
26
|
public class JdbcDatasourceDao {
|
27
|
|
28
|
private static final Log log = LogFactory.getLog(JdbcDatasourceDao.class);
|
29
|
|
30
|
@Value("${datasource.publisher.getsingle.sql}")
|
31
|
private ClassPathResource datasourceDetailsSql;
|
32
|
|
33
|
@Autowired
|
34
|
private BasicDataSource dsDataSource;
|
35
|
|
36
|
public List<String> listIds() throws ApiException {
|
37
|
final List<String> res = Lists.newArrayList();
|
38
|
try {
|
39
|
final String sql = "SELECT id FROM dashboard_ds";
|
40
|
|
41
|
try (final Connection con = getConn(); final PreparedStatement stm = getStm(sql, con); final ResultSet rs = stm.executeQuery()) {
|
42
|
while (rs.next()) {
|
43
|
res.add(rs.getString("id"));
|
44
|
}
|
45
|
}
|
46
|
} catch(SQLException e) {
|
47
|
throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Error querying datasource ids from database", e);
|
48
|
}
|
49
|
return res;
|
50
|
}
|
51
|
|
52
|
private Connection getConn() throws SQLException {
|
53
|
final Connection conn = dsDataSource.getConnection();
|
54
|
conn.setAutoCommit(false);
|
55
|
return conn;
|
56
|
}
|
57
|
|
58
|
private PreparedStatement getStm(final String sql, final Connection con) throws SQLException {
|
59
|
final PreparedStatement stm = con.prepareStatement(sql);
|
60
|
stm.setFetchSize(10);
|
61
|
return stm;
|
62
|
}
|
63
|
|
64
|
protected String obtainQuery(final Resource template, final String id) throws IllegalArgumentException, IOException {
|
65
|
final StringTemplate st = new StringTemplate(IOUtils.toString(template.getInputStream()));
|
66
|
st.setAttribute("id", id);
|
67
|
final String sql = st.toString();
|
68
|
log.debug("Generated query: " + sql);
|
69
|
return sql;
|
70
|
}
|
71
|
|
72
|
}
|