Fixed connection pool handling

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-catalogue/ckan-util-library@129169 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2016-06-20 09:29:58 +00:00
parent a2da9329f0
commit e63f7de731
2 changed files with 89 additions and 35 deletions

View File

@ -57,8 +57,8 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
private String CKAN_TOKEN_SYS;
// use connections pool (multiple threads can use this CKanUtilsImpl instance)
private BasicDataSource ds;
private BasicDataSource connectionPool;
// ckan client
private CkanClient client;
@ -84,12 +84,13 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
// create connection pool
String url = "jdbc:postgresql://" + CKAN_DB_URL + ":" + CKAN_DB_PORT + "/" + CKAN_DB_NAME;
ds = new BasicDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUsername(CKAN_DB_USER);
ds.setPassword(CKAN_DB_PASSWORD);
ds.setUrl(url);
connectionPool = new BasicDataSource();
connectionPool.setDriverClassName("org.postgresql.Driver");
connectionPool.setUsername(CKAN_DB_USER);
connectionPool.setPassword(CKAN_DB_PASSWORD);
connectionPool.setUrl(url);
connectionPool.setInitialSize(10);
// build the client
client = new CkanClient(CKAN_CATALOGUE_URL);
@ -102,7 +103,23 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
*/
private Connection getConnection() throws SQLException{
return ds.getConnection();
return connectionPool.getConnection();
}
/**
* Tries to close a connection
* @param connection
*/
private void closeConnection(Connection connection){
if(connection != null){
try{
connection.close();
}catch(Exception e){
logger.error("Unable to close this connection ", e);
}
}
}
@ -115,9 +132,16 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
String ckanUsername = UtilMethods.fromUsernameToCKanUsername(username);
String apiToReturn = null;
// the connection
Connection connection = null;
try{
connection = getConnection();
String query = "SELECT \"apikey\" FROM \"user\" WHERE \"name\"=? and \"state\"=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(query);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, ckanUsername);
preparedStatement.setString(2, State.ACTIVE.toString().toLowerCase());
@ -130,6 +154,10 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
logger.debug("Api key retrieved for user " + ckanUsername);
}catch(Exception e){
logger.error("Unable to retrieve key for user " + ckanUsername, e);
}finally{
closeConnection(connection);
}
return apiToReturn;
@ -139,9 +167,15 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
public CKanUserWrapper getUserFromApiKey(String apiKey) {
logger.debug("Request user whose api key is = " + apiKey);
CKanUserWrapper user = new CKanUserWrapper();
// the connection
Connection connection = null;
try{
connection = getConnection();
String query = "SELECT * FROM \"user\" WHERE \"apikey\"=? and \"state\"=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(query);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, apiKey);
preparedStatement.setString(2, State.ACTIVE.toString().toLowerCase());
@ -163,6 +197,10 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
}
}catch(Exception e){
logger.error("Unable to retrieve user with api key " + apiKey, e);
}finally{
closeConnection(connection);
}
return user;
}
@ -180,13 +218,18 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
// list to return
List<CkanOrganization> toReturn = new ArrayList<CkanOrganization>();
// the connection
Connection connection = null;
try{
connection = getConnection();
List<String> organizationIds = getOrganizationsIds();
// for each org id, check if the user is included
for (String orgId : organizationIds) {
String query = "SELECT * FROM \"member\" WHERE \"table_id\"=? and \"group_id\"=? and \"table_name\"=? and \"state\"=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(query);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, userId);
preparedStatement.setString(2, orgId);
preparedStatement.setString(3, "user");
@ -200,6 +243,8 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
}
}catch(Exception e){
logger.error("Unable to get user's organizations", e);
}finally{
closeConnection(connection);
}
return toReturn;
}
@ -213,8 +258,14 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
logger.debug("Roles to check are " + rolesToMatch);
Map<String, List<RolesIntoOrganization>> toReturn = new HashMap<String, List<RolesIntoOrganization>>();
// the connection
Connection connection = null;
try{
// get connection
connection = getConnection();
// in order to avoid errors, the username is always converted
String ckanUsername = UtilMethods.fromUsernameToCKanUsername(username);
@ -228,7 +279,7 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
// go to the member table, that says which role has this user into the org
String query = "SELECT * FROM \"member\" WHERE \"table_id\"=? and \"group_id\"=? and \"table_name\"=? and \"state\"=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(query);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, userId);
preparedStatement.setString(2, orgId);
preparedStatement.setString(3, "user");
@ -239,13 +290,14 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
List<RolesIntoOrganization> rolesIntoOrg = new ArrayList<RolesIntoOrganization>();
while(rs.next()){
// check
String role = rs.getString("capacity");
String role = rs.getString("capacity"); // editor, admin, member
if(rolesToMatch.contains(RolesIntoOrganization.valueOf(role.toUpperCase()))){
rolesIntoOrg.add(RolesIntoOrganization.valueOf(role.toUpperCase()));
logger.debug("User " + ckanUsername + " has role " + role + " into organization with id " + orgId);
RolesIntoOrganization enumRole = RolesIntoOrganization.valueOf(role.toUpperCase());
rolesIntoOrg.add(enumRole);
logger.debug("User " + ckanUsername + " has role " + enumRole + " into organization with id " + orgId);
}
break;
}
if(!rolesIntoOrg.isEmpty()){
@ -253,12 +305,14 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
toReturn.put(orgName, rolesIntoOrg);
}
}
logger.debug("Result is " + toReturn);
return toReturn;
}catch(Exception e){
logger.error("Unable to analyze user's roles", e);
}finally{
closeConnection(connection);
}
return null;
@ -361,7 +415,7 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
// get the url and the api key of the user
List<String> result = new ArrayList<String>();
//retrieve the list of available licenses
List<CkanLicense> licenses = client.getLicenseList();
@ -717,34 +771,40 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
String organizationName,
RolesIntoOrganization correspondentRoleToCheck) {
//the connection
Connection connection = null;
try{
connection = getConnection();
// user id
String userId = getUserIdByUsername(ckanUsername);
// we need a checked client
CheckedCkanClient client = new CheckedCkanClient(CKAN_CATALOGUE_URL, CKAN_TOKEN_SYS);
// get the CkanClient to retrieve the organization id from the name
String orgId = client.getOrganization(organizationName).getId();
logger.debug("Organization with name " + organizationName + " has id " + orgId);
String query =
"SELECT * FROM \"member\" WHERE \"table_id\"=? and \"group_id\"=? and \"table_name\"=? and \"state\"=? and \"capacity\"=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(query);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, userId);
preparedStatement.setString(2, orgId);
preparedStatement.setString(3, "user");
preparedStatement.setString(4, State.ACTIVE.toString().toLowerCase());
preparedStatement.setString(5, correspondentRoleToCheck.toString().toLowerCase());
ResultSet rs = preparedStatement.executeQuery();
if(rs.next()) // ok, there is this row
return true;
}catch(Exception e){
logger.error("Unable to check if this role was already set", e);
}finally{
closeConnection(connection);
}
return false;
@ -769,6 +829,6 @@ public class CKanUtilsImpl implements CKanUtilsInterface{
@Override
protected void finalize() throws Throwable {
logger.debug("Closing connection pool on finalize()");
ds.close();
connectionPool.close();
}
}

View File

@ -6,6 +6,7 @@ import java.util.Map;
import org.gcube.datacatalogue.ckanutillibrary.models.CKanUserWrapper;
import org.gcube.datacatalogue.ckanutillibrary.models.RolesIntoOrganization;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import eu.trentorise.opendata.jackan.model.CkanOrganization;
@ -64,12 +65,13 @@ public class TestCKanLib {
}
}
//@Test
public void getGroupsAndRolesByUser() {
@Test
public void getGroupsAndRolesByUser() throws Exception {
logger.debug("Testing getGroupsAndRolesByUser");
String username = "francescomangiacrapa";
String username = "andrea.rossi";
instance = new CKanUtilsImpl("/gcube");
List<RolesIntoOrganization> rolesToMatch = new ArrayList<RolesIntoOrganization>();
rolesToMatch.add(RolesIntoOrganization.ADMIN);
rolesToMatch.add(RolesIntoOrganization.MEMBER);
@ -79,12 +81,4 @@ public class TestCKanLib {
System.out.println("organizations for user " + username + " are " + map);
}
//@Test
public void isRoleAlreadySet() throws Exception{
instance = new CKanUtilsImpl("/gcube");
boolean res = instance.isRoleAlreadySet("andrea_rossi", "devVRE".toLowerCase(), RolesIntoOrganization.EDITOR);
logger.debug("Res is " + res);
}
}