Ensure H2 resources are closed 17/33917/2
authorStephen Kitt <skitt@redhat.com>
Tue, 2 Feb 2016 17:14:04 +0000 (18:14 +0100)
committerStephen Kitt <skitt@redhat.com>
Wed, 3 Feb 2016 08:16:56 +0000 (09:16 +0100)
This patch uses try-with-resources with all database resources
(connections, statements and result sets) to ensure they're closed
correctly in all cases. It drops the re-used dbConnection since that
seems fragile (two threads accessing the store simultaneously might
get the same connection, and one of the threads will close it before
the other has finished), except for tests.

The initial table check/creation is synchronized to avoid
time-of-check to time-of-use races.

Common code is extracted to an AbstractStore.

Exceptions are logged and re-thrown as StoreExceptions with exception
chaining.

Change-Id: Ia63493fcb1361e53a5f3400ee5e2fdf09bccb574
Signed-off-by: Stephen Kitt <skitt@redhat.com>
aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/AbstractStore.java [new file with mode: 0644]
aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/DomainStore.java
aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/GrantStore.java
aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/RoleStore.java
aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/StoreException.java
aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/UserStore.java
aaa-h2-store/src/test/java/org/opendaylight/aaa/h2/persistence/GrantStoreTest.java

diff --git a/aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/AbstractStore.java b/aaa-h2-store/src/main/java/org/opendaylight/aaa/h2/persistence/AbstractStore.java
new file mode 100644 (file)
index 0000000..ba00eb8
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * Copyright © 2016 Red Hat, Inc. and others.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.aaa.h2.persistence;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Base class for H2 stores.
+ */
+abstract class AbstractStore<T> {
+    /**
+     * Logger.
+     */
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractStore.class);
+
+    /**
+     * The name of the table used to represent this store.
+     */
+    private final String tableName;
+
+    /**
+     * Database connection, only used for tests.
+     */
+    Connection dbConnection = null;
+
+    /**
+     * Table types we're interested in (when checking tables' existence).
+     */
+    public static final String[] TABLE_TYPES = new String[] { "TABLE" };
+
+    /**
+     * Creates an instance.
+     *
+     * @param tableName The name of the table being managed.
+     */
+    protected AbstractStore(String tableName) {
+        this.tableName = tableName;
+    }
+
+    /**
+     * Returns a database connection. It is the caller's responsibility to close it. If the managed table does not
+     * exist, it will be created (using {@link #getTableCreationStatement()}).
+     *
+     * @return A database connection.
+     *
+     * @throws StoreException if an error occurs.
+     */
+    protected Connection dbConnect() throws StoreException {
+        Connection conn = H2Store.getConnection(dbConnection);
+        try {
+            // Ensure table check/creation is atomic
+            synchronized (this) {
+                DatabaseMetaData dbm = conn.getMetaData();
+                try (ResultSet rs = dbm.getTables(null, null, tableName, TABLE_TYPES)) {
+                    if (rs.next()) {
+                        LOG.debug("Table {} already exists", tableName);
+                    } else {
+                        LOG.info("Table {} does not exist, creating it", tableName);
+                        try (Statement stmt = conn.createStatement()) {
+                            stmt.executeUpdate(getTableCreationStatement());
+                        }
+                    }
+                }
+            }
+        } catch (SQLException e) {
+            LOG.error("Error connecting to the H2 database", e);
+            throw new StoreException("Cannot connect to database server", e);
+        }
+        return conn;
+    }
+
+    /**
+     * Empties the store.
+     *
+     * @throws StoreException if a connection error occurs.
+     */
+    protected void dbClean() throws StoreException {
+        try (Connection c = dbConnect()) {
+            // The table name can't be a parameter in a prepared statement
+            String sql = "DELETE FROM " + tableName;
+            c.createStatement().execute(sql);
+        } catch (SQLException e) {
+            LOG.error("Error clearing table {}", tableName, e);
+            throw new StoreException("Error clearing table " + tableName, e);
+        }
+    }
+
+    /**
+     * Returns the SQL code required to create the managed table.
+     *
+     * @return The SQL table creation statement.
+     */
+    protected abstract String getTableCreationStatement();
+
+    /**
+     * Lists all the stored items.
+     *
+     * @return The stored item.
+     *
+     * @throws StoreException if an error occurs.
+     */
+    protected List<T> listAll() throws StoreException {
+        List<T> result = new ArrayList<>();
+        String query = "SELECT * FROM " + tableName;
+        try (Connection conn = dbConnect();
+             Statement stmt = conn.createStatement();
+             ResultSet rs = stmt.executeQuery(query)) {
+            while (rs.next()) {
+                result.add(fromResultSet(rs));
+            }
+        } catch (SQLException e) {
+            LOG.error("Error listing all items from {}", tableName, e);
+            throw new StoreException(e);
+        }
+        return result;
+    }
+
+    /**
+     * Lists the stored items returned by the given statement.
+     *
+     * @param ps The statement (which must be ready for execution). It is the caller's reponsibility to close this.
+     *
+     * @return The stored items.
+     *
+     * @throws StoreException if an error occurs.
+     */
+    protected List<T> listFromStatement(PreparedStatement ps) throws StoreException {
+        List<T> result = new ArrayList<>();
+        try (ResultSet rs = ps.executeQuery()) {
+            while (rs.next()) {
+                result.add(fromResultSet(rs));
+            }
+        } catch (SQLException e) {
+            LOG.error("Error listing matching items from {}", tableName, e);
+            throw new StoreException(e);
+        }
+        return result;
+    }
+
+    /**
+     * Extracts the first item returned by the given statement, if any.
+     *
+     * @param ps The statement (which must be ready for execution). It is the caller's reponsibility to close this.
+     *
+     * @return The first item, or {@code null} if none.
+     *
+     * @throws StoreException if an error occurs.
+     */
+    protected T firstFromStatement(PreparedStatement ps) throws StoreException {
+        try (ResultSet rs = ps.executeQuery()) {
+            if (rs.next()) {
+                return fromResultSet(rs);
+            } else {
+                return null;
+            }
+        } catch (SQLException e) {
+            LOG.error("Error listing first matching item from {}", tableName, e);
+            throw new StoreException(e);
+        }
+    }
+
+    /**
+     * Converts a single row in a result set to an instance of the managed type.
+     *
+     * @param rs The result set (which is ready for extraction; {@link ResultSet#next()} must <b>not</b> be called).
+     *
+     * @return The corresponding instance.
+     *
+     * @throws SQLException if an error occurs.
+     */
+    protected abstract T fromResultSet(ResultSet rs) throws SQLException;
+}
index deb7dc95a961cd1e126473ef76f4a921687fb249..9635c559f63f835e6262a181b05a8ec23fec62ab 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
+ * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -11,13 +11,9 @@ package org.opendaylight.aaa.h2.persistence;
 import com.google.common.base.Preconditions;
 
 import java.sql.Connection;
-import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
 
 import org.opendaylight.aaa.api.model.Domain;
 import org.opendaylight.aaa.api.model.Domains;
@@ -29,165 +25,68 @@ import org.slf4j.LoggerFactory;
  * @author peter.mellquist@hp.com
  *
  */
-public class DomainStore {
+public class DomainStore extends AbstractStore<Domain> {
     private static final Logger LOG = LoggerFactory.getLogger(DomainStore.class);
 
-    protected Connection dbConnection = null;
     protected final static String SQL_ID = "domainid";
     protected final static String SQL_NAME = "name";
     protected final static String SQL_DESCR = "description";
     protected final static String SQL_ENABLED = "enabled";
+    private static final String TABLE_NAME = "DOMAINS";
 
     protected DomainStore() {
-    }
-
-    protected Connection getDBConnect() throws StoreException {
-        dbConnection = H2Store.getConnection(dbConnection);
-        return dbConnection;
-    }
-
-    protected void dbClean() throws StoreException, SQLException {
-        Connection c = dbConnect();
-        String sql = "delete from DOMAINS where true";
-        c.createStatement().execute(sql);
-        c.close();
-    }
-
-    protected Connection dbConnect() throws StoreException {
-        Connection conn;
-        try {
-            conn = getDBConnect();
-        } catch (StoreException se) {
-            throw se;
-        }
-        try {
-            DatabaseMetaData dbm = conn.getMetaData();
-            String[] tableTypes = { "TABLE" };
-            ResultSet rs = dbm.getTables(null, null, "DOMAINS", tableTypes);// Caps
-                                                                            // required
-                                                                            // in
-                                                                            // get
-                                                                            // Tables
-            if (rs.next()) {
-                LOG.debug("DOMAINS Table already exists.");
-            } else {
-                LOG.info("in dbConnect, domains Table does not exist, creating table");
-                Statement stmt = null;
-                stmt = conn.createStatement();
-                String sql = "CREATE TABLE DOMAINS " + "(domainid   VARCHAR(128)      PRIMARY KEY,"
-                        + "name        VARCHAR(128)      UNIQUE NOT NULL, "
-                        + "description VARCHAR(128)      , "
-                        + "enabled     INTEGER           NOT NULL)";
-                stmt.executeUpdate(sql);
-                stmt.close();
-            }
-        } catch (SQLException sqe) {
-            throw new StoreException("Cannot connect to database server " + sqe);
-        }
-        return conn;
-    }
-
-    protected void dbClose() {
-        if (dbConnection != null) {
-            try {
-                dbConnection.close();
-            } catch (Exception e) {
-                LOG.error("Cannot close Database Connection", e);
-            }
-        }
+        super(TABLE_NAME);
     }
 
     @Override
-    protected void finalize() throws Throwable {
-        dbClose();
-        super.finalize();
+    protected String getTableCreationStatement() {
+        return "CREATE TABLE DOMAINS "
+                + "(domainid   VARCHAR(128)      PRIMARY KEY,"
+                + "name        VARCHAR(128)      UNIQUE NOT NULL, "
+                + "description VARCHAR(128)      , "
+                + "enabled     INTEGER           NOT NULL)";
     }
 
-    protected Domain rsToDomain(ResultSet rs) throws SQLException {
+    @Override
+    protected Domain fromResultSet(ResultSet rs) throws SQLException {
         Domain domain = new Domain();
-        try {
-            domain.setDomainid(rs.getString(SQL_ID));
-            domain.setName(rs.getString(SQL_NAME));
-            domain.setDescription(rs.getString(SQL_DESCR));
-            domain.setEnabled(rs.getInt(SQL_ENABLED) == 1 ? true : false);
-        } catch (SQLException sqle) {
-            LOG.error("SQL Exception: ", sqle);
-            throw sqle;
-        }
+        domain.setDomainid(rs.getString(SQL_ID));
+        domain.setName(rs.getString(SQL_NAME));
+        domain.setDescription(rs.getString(SQL_DESCR));
+        domain.setEnabled(rs.getInt(SQL_ENABLED) == 1);
         return domain;
     }
 
     protected Domains getDomains() throws StoreException {
         Domains domains = new Domains();
-        List<Domain> domainList = new ArrayList<Domain>();
-        Connection conn = dbConnect();
-        Statement stmt = null;
-        String query = "SELECT * FROM DOMAINS";
-        try {
-            stmt = conn.createStatement();
-            ResultSet rs = stmt.executeQuery(query);
-            while (rs.next()) {
-                Domain domain = rsToDomain(rs);
-                domainList.add(domain);
-            }
-            rs.close();
-            stmt.close();
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
-        }
-        domains.setDomains(domainList);
+        domains.setDomains(listAll());
         return domains;
     }
 
     protected Domains getDomains(String domainName) throws StoreException {
         LOG.debug("getDomains for: {}", domainName);
         Domains domains = new Domains();
-        List<Domain> domainList = new ArrayList<Domain>();
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM DOMAINS WHERE name = ?");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM DOMAINS WHERE name = ?")) {
             pstmt.setString(1, domainName);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            while (rs.next()) {
-                Domain domain = rsToDomain(rs);
-                domainList.add(domain);
-            }
-            rs.close();
-            pstmt.close();
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
+            domains.setDomains(listFromStatement(pstmt));
+        } catch (SQLException e) {
+            LOG.error("Error listing domains matching {}", domainName, e);
+            throw new StoreException("Error listing domains", e);
         }
-        domains.setDomains(domainList);
         return domains;
     }
 
     protected Domain getDomain(String id) throws StoreException {
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM DOMAINS WHERE domainid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM DOMAINS WHERE domainid = ? ")) {
             pstmt.setString(1, id);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            if (rs.next()) {
-                Domain domain = rsToDomain(rs);
-                rs.close();
-                pstmt.close();
-                return domain;
-            } else {
-                rs.close();
-                pstmt.close();
-                return null;
-            }
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
+            return firstFromStatement(pstmt);
+        } catch (SQLException e) {
+            LOG.error("Error retrieving domain {}", id, e);
+            throw new StoreException("Error loading domain", e);
         }
     }
 
@@ -195,10 +94,9 @@ public class DomainStore {
         Preconditions.checkNotNull(domain);
         Preconditions.checkNotNull(domain.getName());
         Preconditions.checkNotNull(domain.isEnabled());
-        Connection conn = dbConnect();
-        try {
-            String query = "insert into DOMAINS (domainid,name,description,enabled) values(?, ?, ?, ?)";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "insert into DOMAINS (domainid,name,description,enabled) values(?, ?, ?, ?)";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, domain.getName());
             statement.setString(2, domain.getName());
             statement.setString(3, domain.getDescription());
@@ -209,10 +107,9 @@ public class DomainStore {
             }
             domain.setDomainid(domain.getName());
             return domain;
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
+        } catch (SQLException e) {
+            LOG.error("Error creating domain {}", domain.getName(), e);
+            throw new StoreException("Error creating domain", e);
         }
     }
 
@@ -232,19 +129,16 @@ public class DomainStore {
             savedDomain.setEnabled(domain.isEnabled());
         }
 
-        Connection conn = dbConnect();
-        try {
-            String query = "UPDATE DOMAINS SET description = ?, enabled = ? WHERE domainid = ?";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "UPDATE DOMAINS SET description = ?, enabled = ? WHERE domainid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, savedDomain.getDescription());
             statement.setInt(2, savedDomain.isEnabled() ? 1 : 0);
             statement.setString(3, savedDomain.getDomainid());
             statement.executeUpdate();
-            statement.close();
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
+        } catch (SQLException e) {
+            LOG.error("Error updating domain {}", domain.getDomainid(), e);
+            throw new StoreException("Error updating domain", e);
         }
 
         return savedDomain;
@@ -255,19 +149,16 @@ public class DomainStore {
         if (deletedDomain == null) {
             return null;
         }
-        Connection conn = dbConnect();
-        try {
-            String query = "DELETE FROM DOMAINS WHERE domainid = ?";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "DELETE FROM DOMAINS WHERE domainid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, deletedDomain.getDomainid());
             int deleteCount = statement.executeUpdate();
             LOG.debug("deleted {} records", deleteCount);
-            statement.close();
             return deletedDomain;
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
+        } catch (SQLException e) {
+            LOG.error("Error deleting domain {}", domainid, e);
+            throw new StoreException("Error deleting domain", e);
         }
     }
 }
index 2bf96a3f0087e3858f9d05c8f638d94d4f578e2c..408bcef6fac98fc3ba9f8c08b40c9e5f8c9f8aa3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
+ * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,13 +9,9 @@
 package org.opendaylight.aaa.h2.persistence;
 
 import java.sql.Connection;
-import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
 
 import org.opendaylight.aaa.api.IDMStoreUtil;
 import org.opendaylight.aaa.api.model.Grant;
@@ -28,75 +24,29 @@ import org.slf4j.LoggerFactory;
  * @author peter.mellquist@hp.com
  *
  */
-public class GrantStore {
+public class GrantStore extends AbstractStore<Grant> {
     private static final Logger LOG = LoggerFactory.getLogger(GrantStore.class);
-    protected Connection dbConnection = null;
+
     protected final static String SQL_ID = "grantid";
     protected final static String SQL_TENANTID = "domainid";
     protected final static String SQL_USERID = "userid";
     protected final static String SQL_ROLEID = "roleid";
+    private static final String TABLE_NAME = "GRANTS";
 
     protected GrantStore() {
-    }
-
-    protected Connection getDBConnect() throws StoreException {
-        dbConnection = H2Store.getConnection(dbConnection);
-        return dbConnection;
-    }
-
-    protected void dbClean() throws StoreException, SQLException {
-        Connection c = dbConnect();
-        String sql = "delete from GRANTS where true";
-        c.createStatement().execute(sql);
-        c.close();
-    }
-
-    protected Connection dbConnect() throws StoreException {
-        Connection conn;
-        try {
-            conn = getDBConnect();
-        } catch (StoreException se) {
-            throw se;
-        }
-        try {
-            DatabaseMetaData dbm = conn.getMetaData();
-            ResultSet rs = dbm.getTables(null, null, "GRANTS", null);
-            if (rs.next()) {
-                LOG.debug("grants Table already exists");
-            } else {
-                LOG.info("grants Table does not exist, creating table");
-                Statement stmt = null;
-                stmt = conn.createStatement();
-                String sql = "CREATE TABLE GRANTS " + "(grantid    VARCHAR(128) PRIMARY KEY,"
-                        + "domainid    VARCHAR(128)         NOT NULL, "
-                        + "userid      VARCHAR(128)         NOT NULL, "
-                        + "roleid      VARCHAR(128)         NOT NULL)";
-                stmt.executeUpdate(sql);
-                stmt.close();
-            }
-        } catch (SQLException sqe) {
-            throw new StoreException("Cannot connect to database server " + sqe);
-        }
-        return conn;
-    }
-
-    protected void dbClose() {
-        if (dbConnection != null) {
-            try {
-                dbConnection.close();
-            } catch (Exception e) {
-                LOG.error("Cannot close Database Connection", e);
-            }
-        }
+        super(TABLE_NAME);
     }
 
     @Override
-    protected void finalize() throws Throwable {
-        dbClose();
-        super.finalize();
+    protected String getTableCreationStatement() {
+        return "CREATE TABLE GRANTS "
+                + "(grantid    VARCHAR(128) PRIMARY KEY,"
+                + "domainid    VARCHAR(128)         NOT NULL, "
+                + "userid      VARCHAR(128)         NOT NULL, "
+                + "roleid      VARCHAR(128)         NOT NULL)";
     }
 
-    protected Grant rsToGrant(ResultSet rs) throws SQLException {
+    protected Grant fromResultSet(ResultSet rs) throws SQLException {
         Grant grant = new Grant();
         try {
             grant.setGrantid(rs.getString(SQL_ID));
@@ -112,112 +62,61 @@ public class GrantStore {
 
     protected Grants getGrants(String did, String uid) throws StoreException {
         Grants grants = new Grants();
-        List<Grant> grantList = new ArrayList<Grant>();
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM grants WHERE domainid = ? AND userid = ?");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn
+                     .prepareStatement("SELECT * FROM grants WHERE domainid = ? AND userid = ?")) {
             pstmt.setString(1, did);
             pstmt.setString(2, uid);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            while (rs.next()) {
-                Grant grant = rsToGrant(rs);
-                grantList.add(grant);
-            }
-            rs.close();
-            pstmt.close();
+            grants.setGrants(listFromStatement(pstmt));
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
-        grants.setGrants(grantList);
         return grants;
     }
 
     protected Grants getGrants(String userid) throws StoreException {
         Grants grants = new Grants();
-        List<Grant> grantList = new ArrayList<Grant>();
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM GRANTS WHERE userid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE userid = ? ")) {
             pstmt.setString(1, userid);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            while (rs.next()) {
-                Grant grant = rsToGrant(rs);
-                grantList.add(grant);
-            }
-            rs.close();
-            pstmt.close();
+            grants.setGrants(listFromStatement(pstmt));
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
-        grants.setGrants(grantList);
         return grants;
     }
 
     protected Grant getGrant(String id) throws StoreException {
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM GRANTS WHERE grantid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE grantid = ? ")) {
             pstmt.setString(1, id);
             LOG.debug("query string: ", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            if (rs.next()) {
-                Grant grant = rsToGrant(rs);
-                rs.close();
-                pstmt.close();
-                return grant;
-            } else {
-                rs.close();
-                pstmt.close();
-                return null;
-            }
+            return firstFromStatement(pstmt);
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 
     protected Grant getGrant(String did, String uid, String rid) throws StoreException {
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM GRANTS WHERE domainid = ? AND userid = ? AND roleid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn
+                     .prepareStatement("SELECT * FROM GRANTS WHERE domainid = ? AND userid = ? AND roleid = ? ")) {
             pstmt.setString(1, did);
             pstmt.setString(2, uid);
             pstmt.setString(3, rid);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            if (rs.next()) {
-                Grant grant = rsToGrant(rs);
-                rs.close();
-                pstmt.close();
-                return grant;
-            } else {
-                rs.close();
-                pstmt.close();
-                return null;
-            }
+            return firstFromStatement(pstmt);
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 
     protected Grant createGrant(Grant grant) throws StoreException {
-        Connection conn = dbConnect();
-        try {
-            String query = "insert into grants  (grantid,domainid,userid,roleid) values(?,?,?,?)";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "insert into grants  (grantid,domainid,userid,roleid) values(?,?,?,?)";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(
                     1,
                     IDMStoreUtil.createGrantid(grant.getUserid(), grant.getDomainid(),
@@ -234,8 +133,6 @@ public class GrantStore {
             return grant;
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 
@@ -245,21 +142,15 @@ public class GrantStore {
             return null;
         }
 
-        Connection conn = dbConnect();
-        try {
-            String query = "DELETE FROM GRANTS WHERE grantid = '" + grantid + "'";
-            Statement st = conn.createStatement();// PreparedStatement statement
-                                                  // =
-                                                  // conn.prepareStatement(query);
-            // statement.setString(1, savedGrant.getGrantid());
-            int deleteCount = st.executeUpdate(query);
+        String query = "DELETE FROM GRANTS WHERE grantid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement ps = conn.prepareStatement(query)) {
+            ps.setString(1, savedGrant.getGrantid());
+            int deleteCount = ps.executeUpdate(query);
             LOG.debug("deleted {} records", deleteCount);
-            st.close();
             return savedGrant;
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 }
index 8e9074f4c70499624c5978a95e7ab50ee34d60c9..adc049ca8d968d8d4fa46b4c7ce40be243b5125a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
+ * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -11,13 +11,9 @@ package org.opendaylight.aaa.h2.persistence;
 import com.google.common.base.Preconditions;
 
 import java.sql.Connection;
-import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
 
 import org.opendaylight.aaa.api.IDMStoreUtil;
 import org.opendaylight.aaa.api.model.Role;
@@ -30,77 +26,29 @@ import org.slf4j.LoggerFactory;
  * @author peter.mellquist@hp.com
  *
  */
-public class RoleStore {
+public class RoleStore extends AbstractStore<Role> {
     private static final Logger LOG = LoggerFactory.getLogger(RoleStore.class);
-    protected Connection dbConnection = null;
+
     protected final static String SQL_ID = "roleid";
     protected final static String SQL_DOMAIN_ID = "domainid";
     protected final static String SQL_NAME = "name";
     protected final static String SQL_DESCR = "description";
-    public final static int MAX_FIELD_LEN = 128;
+    private static final String TABLE_NAME = "ROLES";
 
     protected RoleStore() {
-    }
-
-    protected Connection getDBConnect() throws StoreException {
-        dbConnection = H2Store.getConnection(dbConnection);
-        return dbConnection;
-    }
-
-    protected void dbClean() throws StoreException, SQLException {
-        Connection c = dbConnect();
-        String sql = "delete from ROLES where true";
-        c.createStatement().execute(sql);
-        c.close();
-    }
-
-    protected Connection dbConnect() throws StoreException {
-        Connection conn;
-        try {
-            conn = getDBConnect();
-        } catch (StoreException se) {
-            throw se;
-        }
-        try {
-            DatabaseMetaData dbm = conn.getMetaData();
-            String[] tableTypes = { "TABLE" };
-            ResultSet rs = dbm.getTables(null, null, "ROLES", tableTypes);
-            if (rs.next()) {
-                LOG.debug("roles Table already exists");
-            } else {
-                LOG.info("roles Table does not exist, creating table");
-                Statement stmt = null;
-                stmt = conn.createStatement();
-                String sql = "CREATE TABLE ROLES " + "(roleid     VARCHAR(128)   PRIMARY KEY,"
-                        + "name        VARCHAR(128)   NOT NULL, "
-                        + "domainid    VARCHAR(128)   NOT NULL, "
-                        + "description VARCHAR(128)      NOT NULL)";
-                stmt.executeUpdate(sql);
-                stmt.close();
-            }
-        } catch (SQLException sqe) {
-            throw new StoreException("Cannot connect to database server " + sqe);
-        }
-        return conn;
-    }
-
-    protected void dbClose() {
-        if (dbConnection != null) {
-            try {
-                dbConnection.close();
-            } catch (Exception e) {
-                LOG.error("Cannot close Database Connection", e);
-            }
-        }
+        super(TABLE_NAME);
     }
 
     @Override
-    protected void finalize() throws Throwable {
-        dbClose();
-        super.finalize();
+    protected String getTableCreationStatement() {
+        return "CREATE TABLE ROLES "
+                + "(roleid     VARCHAR(128)   PRIMARY KEY,"
+                + "name        VARCHAR(128)   NOT NULL, "
+                + "domainid    VARCHAR(128)   NOT NULL, "
+                + "description VARCHAR(128)      NOT NULL)";
     }
 
-    protected Role rsToRole(ResultSet rs) throws SQLException {
+    protected Role fromResultSet(ResultSet rs) throws SQLException {
         Role role = new Role();
         try {
             role.setRoleid(rs.getString(SQL_ID));
@@ -116,50 +64,19 @@ public class RoleStore {
 
     protected Roles getRoles() throws StoreException {
         Roles roles = new Roles();
-        List<Role> roleList = new ArrayList<Role>();
-        Connection conn = dbConnect();
-        Statement stmt = null;
-        String query = "SELECT * FROM roles";
-        try {
-            stmt = conn.createStatement();
-            ResultSet rs = stmt.executeQuery(query);
-            while (rs.next()) {
-                Role role = rsToRole(rs);
-                roleList.add(role);
-            }
-            rs.close();
-            stmt.close();
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
-        }
-        roles.setRoles(roleList);
+        roles.setRoles(listAll());
         return roles;
     }
 
     protected Role getRole(String id) throws StoreException {
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM ROLES WHERE roleid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn
+                     .prepareStatement("SELECT * FROM ROLES WHERE roleid = ? ")) {
             pstmt.setString(1, id);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            if (rs.next()) {
-                Role role = rsToRole(rs);
-                rs.close();
-                pstmt.close();
-                return role;
-            } else {
-                rs.close();
-                pstmt.close();
-                return null;
-            }
+            return firstFromStatement(pstmt);
         } catch (SQLException s) {
             throw new StoreException("SQL Exception: " + s);
-        } finally {
-            dbClose();
         }
     }
 
@@ -167,10 +84,9 @@ public class RoleStore {
         Preconditions.checkNotNull(role);
         Preconditions.checkNotNull(role.getName());
         Preconditions.checkNotNull(role.getDomainid());
-        Connection conn = dbConnect();
-        try {
-            String query = "insert into roles (roleid,domainid,name,description) values(?,?,?,?)";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "insert into roles (roleid,domainid,name,description) values(?,?,?,?)";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             role.setRoleid(IDMStoreUtil.createRoleid(role.getName(), role.getDomainid()));
             statement.setString(1, role.getRoleid());
             statement.setString(2, role.getDomainid());
@@ -183,8 +99,6 @@ public class RoleStore {
             return role;
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 
@@ -202,18 +116,14 @@ public class RoleStore {
             savedRole.setName(role.getName());
         }
 
-        Connection conn = dbConnect();
-        try {
-            String query = "UPDATE roles SET description = ? WHERE roleid = ?";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "UPDATE roles SET description = ? WHERE roleid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, savedRole.getDescription());
             statement.setString(2, savedRole.getRoleid());
             statement.executeUpdate();
-            statement.close();
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
 
         return savedRole;
@@ -225,19 +135,15 @@ public class RoleStore {
             return null;
         }
 
-        Connection conn = dbConnect();
-        try {
-            String query = "DELETE FROM DOMAINS WHERE domainid = ?";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "DELETE FROM DOMAINS WHERE domainid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, savedRole.getRoleid());
             int deleteCount = statement.executeUpdate(query);
             LOG.debug("deleted {} records", deleteCount);
-            statement.close();
             return savedRole;
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 }
index d6293330d5fa0f94408a9726720f30a6283553d0..7d2f2b9a31e6fe86aacac743b83f388bdb11868f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
+ * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,25 +9,21 @@
 package org.opendaylight.aaa.h2.persistence;
 
 /**
+ * Exception indicating an error in an H2 data store.
  *
  * @author peter.mellquist@hp.com
- *
  */
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 public class StoreException extends Exception {
-    /**
-     *
-     */
-    private static final long serialVersionUID = 1403628228591780351L;
-
-    private static final Logger LOG = LoggerFactory.getLogger(StoreException.class);
+    public StoreException(String message) {
+        super(message);
+    }
 
-    public String message = null;
+    public StoreException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-    public StoreException(String msg) {
-        LOG.error(msg);
-        message = new String(msg);
+    public StoreException(Throwable cause) {
+        super(cause);
     }
 }
index 8a98d5547fb4fb0f1fc922460aa4dbeb3fbcb3e6..dc5e4c00d411fece7988b173381c0145a255a7e3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
+ * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -11,13 +11,9 @@ package org.opendaylight.aaa.h2.persistence;
 import com.google.common.base.Preconditions;
 
 import java.sql.Connection;
-import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
 
 import org.opendaylight.aaa.api.IDMStoreUtil;
 import org.opendaylight.aaa.api.SHA256Calculator;
@@ -31,9 +27,9 @@ import org.slf4j.LoggerFactory;
  * @author peter.mellquist@hp.com
  *
  */
-public class UserStore {
+public class UserStore extends AbstractStore<User> {
     private static final Logger LOG = LoggerFactory.getLogger(UserStore.class);
-    protected Connection dbConnection = null;
+
     protected final static String SQL_ID = "userid";
     protected final static String SQL_DOMAIN_ID = "domainid";
     protected final static String SQL_NAME = "name";
@@ -42,74 +38,27 @@ public class UserStore {
     protected final static String SQL_DESCR = "description";
     protected final static String SQL_ENABLED = "enabled";
     protected final static String SQL_SALT = "salt";
-    public final static int MAX_FIELD_LEN = 128;
+    private static final String TABLE_NAME = "USERS";
 
     protected UserStore() {
-    }
-
-    protected Connection getDBConnect() throws StoreException {
-        dbConnection = H2Store.getConnection(dbConnection);
-        return dbConnection;
-    }
-
-    protected void dbClean() throws StoreException, SQLException {
-        Connection c = dbConnect();
-        String sql = "delete from users where true";
-        c.createStatement().execute(sql);
-        c.close();
-    }
-
-    protected Connection dbConnect() throws StoreException {
-        Connection conn;
-        try {
-            conn = getDBConnect();
-        } catch (StoreException se) {
-            throw se;
-        }
-        try {
-            DatabaseMetaData dbm = conn.getMetaData();
-            String[] tableTypes = { "TABLE" };
-            ResultSet rs = dbm.getTables(null, null, "USERS", tableTypes);
-            if (rs.next()) {
-                LOG.debug("users Table already exists");
-            } else {
-                LOG.info("users Table does not exist, creating table");
-                Statement stmt = null;
-                stmt = conn.createStatement();
-                String sql = "CREATE TABLE users " + "(userid    VARCHAR(128) PRIMARY KEY,"
-                        + "name       VARCHAR(128)      NOT NULL, "
-                        + "domainid   VARCHAR(128)      NOT NULL, "
-                        + "email      VARCHAR(128)      NOT NULL, "
-                        + "password   VARCHAR(128)      NOT NULL, "
-                        + "description VARCHAR(128)     NOT NULL, "
-                        + "salt        VARCHAR(15)      NOT NULL, "
-                        + "enabled     INTEGER          NOT NULL)";
-                stmt.executeUpdate(sql);
-                stmt.close();
-            }
-        } catch (SQLException sqe) {
-            throw new StoreException("Cannot connect to database server " + sqe);
-        }
-        return conn;
-    }
-
-    protected void dbClose() {
-        if (dbConnection != null) {
-            try {
-                dbConnection.close();
-            } catch (Exception e) {
-                LOG.error("Cannot close Database Connection", e);
-            }
-        }
+        super(TABLE_NAME);
     }
 
     @Override
-    protected void finalize() throws Throwable {
-        dbClose();
-        super.finalize();
+    protected String getTableCreationStatement() {
+        return "CREATE TABLE users "
+                + "(userid    VARCHAR(128) PRIMARY KEY,"
+                + "name       VARCHAR(128)      NOT NULL, "
+                + "domainid   VARCHAR(128)      NOT NULL, "
+                + "email      VARCHAR(128)      NOT NULL, "
+                + "password   VARCHAR(128)      NOT NULL, "
+                + "description VARCHAR(128)     NOT NULL, "
+                + "salt        VARCHAR(15)      NOT NULL, "
+                + "enabled     INTEGER          NOT NULL)";
     }
 
-    protected User rsToUser(ResultSet rs) throws SQLException {
+    @Override
+    protected User fromResultSet(ResultSet rs) throws SQLException {
         User user = new User();
         try {
             user.setUserid(rs.getString(SQL_ID));
@@ -118,7 +67,7 @@ public class UserStore {
             user.setEmail(rs.getString(SQL_EMAIL));
             user.setPassword(rs.getString(SQL_PASSWORD));
             user.setDescription(rs.getString(SQL_DESCR));
-            user.setEnabled(rs.getInt(SQL_ENABLED) == 1 ? true : false);
+            user.setEnabled(rs.getInt(SQL_ENABLED) == 1);
             user.setSalt(rs.getString(SQL_SALT));
         } catch (SQLException sqle) {
             LOG.error("SQL Exception: ", sqle);
@@ -129,25 +78,7 @@ public class UserStore {
 
     protected Users getUsers() throws StoreException {
         Users users = new Users();
-        List<User> userList = new ArrayList<User>();
-        Connection conn = dbConnect();
-        Statement stmt = null;
-        String query = "SELECT * FROM users";
-        try {
-            stmt = conn.createStatement();
-            ResultSet rs = stmt.executeQuery(query);
-            while (rs.next()) {
-                User user = rsToUser(rs);
-                userList.add(user);
-            }
-            rs.close();
-            stmt.close();
-        } catch (SQLException s) {
-            throw new StoreException("SQL Exception");
-        } finally {
-            dbClose();
-        }
-        users.setUsers(userList);
+        users.setUsers(listAll());
         return users;
     }
 
@@ -155,51 +86,25 @@ public class UserStore {
         LOG.debug("getUsers for: {} in domain {}", username, domain);
 
         Users users = new Users();
-        List<User> userList = new ArrayList<User>();
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM USERS WHERE userid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE userid = ? ")) {
             pstmt.setString(1, IDMStoreUtil.createUserid(username, domain));
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            while (rs.next()) {
-                User user = rsToUser(rs);
-                userList.add(user);
-            }
-            rs.close();
-            pstmt.close();
+            users.setUsers(listFromStatement(pstmt));
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
-        users.setUsers(userList);
         return users;
     }
 
     protected User getUser(String id) throws StoreException {
-        Connection conn = dbConnect();
-        try {
-            PreparedStatement pstmt = conn
-                    .prepareStatement("SELECT * FROM USERS WHERE userid = ? ");
+        try (Connection conn = dbConnect();
+             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE userid = ? ")) {
             pstmt.setString(1, id);
             LOG.debug("query string: {}", pstmt.toString());
-            ResultSet rs = pstmt.executeQuery();
-            if (rs.next()) {
-                User user = rsToUser(rs);
-                rs.close();
-                pstmt.close();
-                return user;
-            } else {
-                rs.close();
-                pstmt.close();
-                return null;
-            }
+            return firstFromStatement(pstmt);
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 
@@ -208,11 +113,10 @@ public class UserStore {
         Preconditions.checkNotNull(user.getName());
         Preconditions.checkNotNull(user.getDomainid());
 
-        Connection conn = dbConnect();
-        try {
-            user.setSalt(SHA256Calculator.generateSALT());
-            String query = "insert into users (userid,domainid,name,email,password,description,enabled,salt) values(?,?,?,?,?,?,?,?)";
-            PreparedStatement statement = conn.prepareStatement(query);
+        user.setSalt(SHA256Calculator.generateSALT());
+        String query = "insert into users (userid,domainid,name,email,password,description,enabled,salt) values(?,?,?,?,?,?,?,?)";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             user.setUserid(IDMStoreUtil.createUserid(user.getName(), user.getDomainid()));
             statement.setString(1, user.getUserid());
             statement.setString(2, user.getDomainid());
@@ -229,8 +133,6 @@ public class UserStore {
             return user;
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 
@@ -257,21 +159,17 @@ public class UserStore {
             savedUser.setPassword(SHA256Calculator.getSHA256(user.getPassword(), user.getSalt()));
         }
 
-        Connection conn = dbConnect();
-        try {
-            String query = "UPDATE users SET email = ?, password = ?, description = ?, enabled = ? WHERE userid = ?";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "UPDATE users SET email = ?, password = ?, description = ?, enabled = ? WHERE userid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, savedUser.getEmail());
             statement.setString(2, savedUser.getPassword());
             statement.setString(3, savedUser.getDescription());
             statement.setInt(4, savedUser.isEnabled() ? 1 : 0);
             statement.setString(5, savedUser.getUserid());
             statement.executeUpdate();
-            statement.close();
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
 
         return savedUser;
@@ -283,19 +181,15 @@ public class UserStore {
             return null;
         }
 
-        Connection conn = dbConnect();
-        try {
-            String query = "DELETE FROM USERS WHERE userid = ?";
-            PreparedStatement statement = conn.prepareStatement(query);
+        String query = "DELETE FROM USERS WHERE userid = ?";
+        try (Connection conn = dbConnect();
+             PreparedStatement statement = conn.prepareStatement(query)) {
             statement.setString(1, savedUser.getUserid());
             int deleteCount = statement.executeUpdate(query);
             LOG.debug("deleted {} records", deleteCount);
-            statement.close();
             return savedUser;
         } catch (SQLException s) {
             throw new StoreException("SQL Exception : " + s);
-        } finally {
-            dbClose();
         }
     }
 }
index bf66608c9e1bf665bbe4da7f8b965137764d1554..168b67e2bc48857902a303ff8885ad0f64111f96 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
+ * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -23,7 +23,6 @@ import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mockito;
 import org.opendaylight.aaa.api.model.Grants;
-import org.opendaylight.aaa.h2.persistence.GrantStore;
 
 public class GrantStoreTest {
 
@@ -40,11 +39,12 @@ public class GrantStoreTest {
     @Test
     public void getGrantsTest() throws Exception {
         // Setup Mock Behavior
+        String[] tableTypes = { "TABLE" };
         Mockito.when(connectionMock.isClosed()).thenReturn(false);
         DatabaseMetaData dbmMock = mock(DatabaseMetaData.class);
         Mockito.when(connectionMock.getMetaData()).thenReturn(dbmMock);
         ResultSet rsUserMock = mock(ResultSet.class);
-        Mockito.when(dbmMock.getTables(null, null, "GRANTS", null)).thenReturn(rsUserMock);
+        Mockito.when(dbmMock.getTables(null, null, "GRANTS", tableTypes)).thenReturn(rsUserMock);
         Mockito.when(rsUserMock.next()).thenReturn(true);
 
         PreparedStatement pstmtMock = mock(PreparedStatement.class);