Merge "Fix JDK8 compatibility"
[aaa.git] / aaa-idmlight / src / main / java / org / opendaylight / aaa / idm / persistence / GrantStore.java
1 /*
2  * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.aaa.idm.persistence;
10
11 /**
12  *
13  * @author peter.mellquist@hp.com
14  *
15  */
16
17 import java.sql.Connection;
18 import java.sql.DatabaseMetaData;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.sql.Statement;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.opendaylight.aaa.idm.IdmLightApplication;
27 import org.opendaylight.aaa.idm.model.Grant;
28 import org.opendaylight.aaa.idm.model.Grants;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class GrantStore {
33    private static Logger logger = LoggerFactory.getLogger(GrantStore.class);
34    protected Connection  dbConnection = null;
35    protected final static String SQL_ID             = "grantid";
36    protected final static String SQL_TENANTID       = "domainid";
37    protected final static String SQL_USERID         = "userid";
38    protected final static String SQL_ROLEID         = "roleid";
39
40    protected Connection getDBConnect() throws StoreException {
41       dbConnection = IdmLightApplication.getConnection(dbConnection);
42       return dbConnection;
43    }
44
45    protected void dbClean() throws StoreException, SQLException{
46       Connection c = dbConnect();
47       String sql = "delete from GRANTS where true";
48       c.createStatement().execute(sql);
49       c.close();
50    }
51
52    protected Connection dbConnect() throws StoreException {
53       Connection conn;
54       try {
55          conn = getDBConnect();
56       }
57       catch (StoreException se) {
58          throw se;
59       }
60       try {
61          DatabaseMetaData dbm = conn.getMetaData();
62          ResultSet rs = dbm.getTables(null, null, "GRANTS", null);
63          if (rs.next()) {
64             debug("grants Table already exists");
65          }
66          else
67          {
68             logger.info("grants Table does not exist, creating table");
69             Statement stmt = null;
70             stmt = conn.createStatement();
71             String sql = "CREATE TABLE GRANTS " +
72                          "(grantid    VARCHAR(128) PRIMARY KEY," +
73                          "domainid    VARCHAR(128)         NOT NULL, " +
74                          "userid      VARCHAR(128)         NOT NULL, " +
75                          "roleid      VARCHAR(128)         NOT NULL)" ;
76            stmt.executeUpdate(sql);
77            stmt.close();
78          }
79       }
80       catch (SQLException sqe) {
81          throw new StoreException("Cannot connect to database server "+ sqe);
82       }
83       return conn;
84    }
85
86
87
88
89    protected void dbClose() {
90       if (dbConnection != null)
91       {
92          try {
93             dbConnection.close ();
94           }
95           catch (Exception e) {
96             logger.error("Cannot close Database Connection " + e);
97           }
98        }
99    }
100
101    @Override
102 protected void finalize () throws Throwable {
103       dbClose();
104       super.finalize();
105    }
106
107    protected Grant rsToGrant(ResultSet rs) throws SQLException {
108       Grant grant = new Grant();
109       try {
110          grant.setGrantid(rs.getString(SQL_ID));
111          grant.setDomainid(rs.getString(SQL_TENANTID));
112          grant.setUserid(rs.getString(SQL_USERID));
113          grant.setRoleid(rs.getString(SQL_ROLEID));
114       }
115       catch (SQLException sqle) {
116          logger.error( "SQL Exception : " + sqle);
117             throw sqle;
118       }
119       return grant;
120    }
121
122    public Grants getGrants(String did, String uid) throws StoreException {
123       Grants grants = new Grants();
124       List<Grant> grantList = new ArrayList<Grant>();
125       Connection conn = dbConnect();
126       try {
127          PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM grants WHERE domainid = ? AND userid = ?");
128          pstmt.setString(1, did);
129          pstmt.setString(2, uid);
130          debug("query string: " + pstmt.toString());
131          ResultSet rs = pstmt.executeQuery();
132          while (rs.next()) {
133             Grant grant = rsToGrant(rs);
134             grantList.add(grant);
135          }
136          rs.close();
137          pstmt.close();
138       }
139       catch (SQLException s) {
140          throw new StoreException("SQL Exception : " + s);
141       }
142       finally {
143          dbClose();
144        }
145       grants.setGrants(grantList);
146       return grants;
147    }
148
149    public Grants getGrants(int uid) throws StoreException {
150       Grants grants = new Grants();
151       List<Grant> grantList = new ArrayList<Grant>();
152       Connection conn = dbConnect();
153       try {
154          PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE userid = ? ");
155          pstmt.setInt(1, uid);
156          debug("query string: " + pstmt.toString());
157          ResultSet rs = pstmt.executeQuery();
158          while (rs.next()) {
159             Grant grant = rsToGrant(rs);
160             grantList.add(grant);
161          }
162          rs.close();
163          pstmt.close();
164       }
165       catch (SQLException s) {
166          throw new StoreException("SQL Exception : " + s);
167       }
168       finally {
169          dbClose();
170       }
171       grants.setGrants(grantList);
172       return grants;
173    }
174
175
176    public Grant  getGrant(String id) throws StoreException {
177       Connection conn = dbConnect();
178       try {
179           PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE grantid = ? ");
180           pstmt.setString(1, id);
181           debug("query string: " + pstmt.toString());
182           ResultSet rs = pstmt.executeQuery();
183          if (rs.next()) {
184             Grant grant = rsToGrant(rs);
185             rs.close();
186             pstmt.close();
187             return grant;
188          }
189          else {
190             rs.close();
191             pstmt.close();
192             return null;
193          }
194       }
195       catch (SQLException s) {
196          throw new StoreException("SQL Exception : " + s);
197       }
198       finally {
199          dbClose();
200         }
201    }
202
203    public Grant getGrant(String did,String uid,String rid) throws StoreException {
204       Connection conn = dbConnect();
205       try {
206           PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE domainid = ? AND userid = ? AND roleid = ? ");
207           pstmt.setString(1, did);
208           pstmt.setString(2, uid);
209           pstmt.setString(3, rid);
210           debug("query string: " + pstmt.toString());
211           ResultSet rs = pstmt.executeQuery();
212          if (rs.next()) {
213             Grant grant = rsToGrant(rs);
214             rs.close();
215             pstmt.close();
216             return grant;
217          }
218          else {
219             rs.close();
220             pstmt.close();
221             return null;
222          }
223       }
224       catch (SQLException s) {
225          throw new StoreException("SQL Exception : " + s);
226       }
227       finally {
228          dbClose();
229         }
230    }
231
232
233    public Grant createGrant(Grant grant) throws StoreException {
234        Connection conn = dbConnect();
235        try {
236           String query = "insert into grants  (grantid,domainid,userid,roleid) values(?,?,?,?)";
237           PreparedStatement statement = conn.prepareStatement(query);
238           statement.setString(1,grant.getUserid()+"@"+grant.getDomainid()+"@"+grant.getRoleid());
239           statement.setString(2,grant.getDomainid());
240           statement.setString(3,grant.getUserid());
241           statement.setString(4,grant.getRoleid());
242           int affectedRows = statement.executeUpdate();
243           if (affectedRows == 0) {
244              throw new StoreException("Creating grant failed, no rows affected.");
245           }
246           return grant;
247        }
248        catch (SQLException s) {
249           throw new StoreException("SQL Exception : " + s);
250        }
251        finally {
252           dbClose();
253          }
254    }
255
256    public Grant deleteGrant(Grant grant) throws StoreException {
257       Grant savedGrant = this.getGrant(grant.getGrantid());
258       if (savedGrant==null) {
259          return null;
260       }
261
262       Connection conn = dbConnect();
263       try {
264           String query = "DELETE FROM GRANTS WHERE grantid = ?";
265           PreparedStatement statement = conn.prepareStatement(query);
266           statement.setString(1, savedGrant.getGrantid());
267          int deleteCount = statement.executeUpdate(query);
268          debug("deleted " + deleteCount + " records");
269          statement.close();
270          return savedGrant;
271       }
272       catch (SQLException s) {
273          throw new StoreException("SQL Exception : " + s);
274       }
275       finally {
276           dbClose();
277         }
278    }
279
280    private static final void debug(String msg) {
281        if (logger.isDebugEnabled()) {
282            logger.debug(msg);
283        }
284    }
285 }
286