--- /dev/null
+/*
+ * 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;
+}
/*
- * 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,
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;
* @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);
}
}
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());
}
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);
}
}
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;
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);
}
}
}
/*
- * 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,
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;
* @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));
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(),
return grant;
} catch (SQLException s) {
throw new StoreException("SQL Exception : " + s);
- } finally {
- dbClose();
}
}
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();
}
}
}
/*
- * 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,
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;
* @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));
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();
}
}
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());
return role;
} catch (SQLException s) {
throw new StoreException("SQL Exception : " + s);
- } finally {
- dbClose();
}
}
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;
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();
}
}
}
/*
- * 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,
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);
}
}
/*
- * 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,
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;
* @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";
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));
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);
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;
}
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();
}
}
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());
return user;
} catch (SQLException s) {
throw new StoreException("SQL Exception : " + s);
- } finally {
- dbClose();
}
}
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;
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();
}
}
}
/*
- * 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,
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 {
@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);