Merge "Fix JDK8 compatibility"
[aaa.git] / aaa-idmlight / src / main / java / org / opendaylight / aaa / idm / persistence / RoleStore.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.Role;
28 import org.opendaylight.aaa.idm.model.Roles;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import com.google.common.base.Preconditions;
33
34 public class RoleStore {
35    private static Logger logger = LoggerFactory.getLogger(RoleStore.class);
36    protected Connection  dbConnection = null;
37    protected final static String SQL_ID             = "roleid";
38    protected final static String SQL_DOMAIN_ID      = "domainid";
39    protected final static String SQL_NAME           = "name";
40    protected final static String SQL_DESCR          = "description";
41    public final static int       MAX_FIELD_LEN      = 128;
42
43    protected Connection getDBConnect() throws StoreException {
44       dbConnection = IdmLightApplication.getConnection(dbConnection);
45       return dbConnection;
46    }
47
48    protected void dbClean() throws StoreException, SQLException{
49       Connection c = dbConnect();
50       String sql = "delete from ROLES where true";
51       c.createStatement().execute(sql);
52       c.close();
53    }
54
55    protected Connection dbConnect() throws StoreException {
56       Connection conn;
57       try {
58          conn = getDBConnect();
59       }
60       catch (StoreException se) {
61          throw se;
62       }
63       try {
64          DatabaseMetaData dbm = conn.getMetaData();
65          String[] tableTypes = {"TABLE"};
66          ResultSet rs = dbm.getTables(null, null, "ROLES", tableTypes);
67          if (rs.next()) {
68             debug("roles Table already exists");
69          }
70          else
71          {
72             logger.info("roles Table does not exist, creating table");
73             Statement stmt = null;
74             stmt = conn.createStatement();
75             String sql = "CREATE TABLE ROLES " +
76                          "(roleid     VARCHAR(128)   PRIMARY KEY," +
77                          "name        VARCHAR(128)   NOT NULL, " +
78                          "domainid    VARCHAR(128)   NOT NULL, " +
79                          "description VARCHAR(128)      NOT NULL)";
80            stmt.executeUpdate(sql);
81            stmt.close();
82          }
83       }
84       catch (SQLException sqe) {
85          throw new StoreException("Cannot connect to database server "+ sqe);
86       }
87       return conn;
88    }
89
90
91    protected void dbClose() {
92       if (dbConnection != null)
93       {
94          try {
95             dbConnection.close ();
96           }
97           catch (Exception e) {
98             logger.error("Cannot close Database Connection " + e);
99           }
100        }
101    }
102
103    @Override
104 protected void finalize () throws Throwable {
105       dbClose();
106       super.finalize();
107    }
108
109    protected  Role rsToRole(ResultSet rs) throws SQLException {
110       Role role = new Role();
111       try {
112          role.setRoleid(rs.getString(SQL_ID));
113          role.setDomainID(rs.getString(SQL_DOMAIN_ID));
114          role.setName(rs.getString(SQL_NAME));
115          role.setDescription(rs.getString(SQL_DESCR));
116       }
117       catch (SQLException sqle) {
118          logger.error( "SQL Exception : " + sqle);
119             throw sqle;
120       }
121       return role;
122    }
123
124    public Roles getRoles() throws StoreException {
125       Roles roles = new Roles();
126       List<Role> roleList = new ArrayList<Role>();
127       Connection conn = dbConnect();
128       Statement stmt=null;
129       String query = "SELECT * FROM roles";
130       try {
131          stmt=conn.createStatement();
132          ResultSet rs=stmt.executeQuery(query);
133          while (rs.next()) {
134             Role role = rsToRole(rs);
135             roleList.add(role);
136          }
137          rs.close();
138          stmt.close();
139       }
140       catch (SQLException s) {
141          throw new StoreException("SQL Exception : " + s);
142       }
143       finally {
144          dbClose();
145        }
146       roles.setRoles(roleList);
147       return roles;
148    }
149
150    public Role getRole(String id) throws StoreException {
151       Connection conn = dbConnect();
152       try {
153          PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM ROLES WHERE roleid = ? ");
154          pstmt.setString(1, id);
155          debug("query string: " + pstmt.toString());
156          ResultSet rs = pstmt.executeQuery();
157          if (rs.next()) {
158             Role role = rsToRole(rs);
159             rs.close();
160             pstmt.close();
161             return role;
162          }
163          else {
164             rs.close();
165             pstmt.close();
166             return null;
167          }
168       }
169       catch (SQLException s) {
170          throw new StoreException("SQL Exception : " + s);
171       }
172       finally {
173          dbClose();
174        }
175    }
176
177    public Role createRole(Role role) throws StoreException {
178            Preconditions.checkNotNull(role);
179            Preconditions.checkNotNull(role.getName());
180            Preconditions.checkNotNull(role.getDomainID());
181        Connection conn = dbConnect();
182        try {
183           String query = "insert into roles (roleid,domainid,name,description) values(?,?,?,?)";
184           PreparedStatement statement = conn.prepareStatement(query);
185           role.setRoleid(role.getName()+"@"+role.getDomainID());
186           statement.setString(1, role.getRoleid());
187           statement.setString(2, role.getDomainID());
188           statement.setString(3,role.getName());
189           statement.setString(4,role.getDescription());
190           int affectedRows = statement.executeUpdate();
191           if (affectedRows == 0) {
192              throw new StoreException("Creating role failed, no rows affected.");
193           }
194           return role;
195        }
196        catch (SQLException s) {
197           throw new StoreException("SQL Exception : " + s);
198        }
199        finally {
200           dbClose();
201         }
202    }
203
204    public Role putRole(Role role) throws StoreException {
205
206       Role savedRole = this.getRole(role.getRoleid());
207       if (savedRole==null) {
208          return null;
209       }
210
211       if (role.getDescription()!=null) {
212          savedRole.setDescription(role.getDescription());
213       }
214       if (role.getName()!=null) {
215          savedRole.setName(role.getName());
216       }
217
218       Connection conn = dbConnect();
219       try {
220          String query = "UPDATE roles SET description = ? WHERE roleid = ?";
221          PreparedStatement statement = conn.prepareStatement(query);
222          statement.setString(1, savedRole.getDescription());
223          statement.setString(2,savedRole.getRoleid());
224          statement.executeUpdate();
225          statement.close();
226       }
227       catch (SQLException s) {
228          throw new StoreException("SQL Exception : " + s);
229       }
230       finally {
231          dbClose();
232        }
233
234       return savedRole;
235    }
236
237    public Role deleteRole(Role role) throws StoreException {
238       Role savedRole = this.getRole(role.getRoleid());
239       if (savedRole==null) {
240          return null;
241       }
242
243       Connection conn = dbConnect();
244       try {
245          String query = "DELETE FROM DOMAINS WHERE domainid = ?";
246          PreparedStatement statement = conn.prepareStatement(query);
247          statement.setString(1, savedRole.getRoleid());
248          int deleteCount = statement.executeUpdate(query);
249          debug("deleted " + deleteCount + " records");
250          statement.close();
251          return savedRole;
252       }
253       catch (SQLException s) {
254          throw new StoreException("SQL Exception : " + s);
255       }
256       finally {
257           dbClose();
258        }
259    }
260
261    private static final void debug(String msg) {
262        if (logger.isDebugEnabled()) {
263            logger.debug(msg);
264        }
265    }
266 }
267