Fixed bug that caused search string to be corrupted after multiple queries. (patch...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / attrresolv / provider / JDBCDataConnector.java
1 /*
2  * Copyright (c) 2003 National Research Council of Canada
3  *
4  * Permission is hereby granted, free of charge, to any person 
5  * obtaining a copy of this software and associated documentation 
6  * files (the "Software"), to deal in the Software without 
7  * restriction, including without limitation the rights to use, 
8  * copy, modify, merge, publish, distribute, sublicense, and/or 
9  * sell copies of the Software, and to permit persons to whom the 
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be 
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
17  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
19  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
20  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */
25
26 package edu.internet2.middleware.shibboleth.aa.attrresolv.provider;
27
28 import java.lang.reflect.InvocationTargetException;
29 import java.lang.reflect.Method;
30 import java.security.Principal;
31 import java.sql.Connection;
32 import java.sql.DriverManager;
33 import java.sql.ResultSet;
34 import java.sql.ResultSetMetaData;
35 import java.sql.SQLException;
36 import java.sql.Statement;
37 import java.util.Hashtable;
38
39 import javax.naming.directory.Attributes;
40 import javax.naming.directory.BasicAttribute;
41 import javax.naming.directory.BasicAttributes;
42
43 import org.apache.log4j.Logger;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.NodeList;
46
47 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
48 import edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn;
49 import edu.internet2.middleware.shibboleth.aa.attrresolv.ResolutionPlugInException;
50
51 /*
52  * Built at the Canada Institute for Scientific and Technical Information (CISTI 
53  * <ahref="http://www.cisti-icist.nrc-cnrc.gc.ca/">http://www.cisti-icist.nrc-cnrc.gc.ca/</a>, 
54  * the National Research Council Canada 
55  * (NRC <a href="http://www.nrc-cnrc.gc.ca/">http://www.nrc-cnrc.gc.ca/</a>)
56  * by David Dearman, COOP student from Dalhousie University,
57  * under the direction of Glen Newton, Head research (IT)
58  * <ahref="mailto:glen.newton@nrc-cnrc.gc.ca">glen.newton@nrc-cnrc.gc.ca</a>. 
59  */
60
61 /**
62  * Data Connector that uses JDBC to access user attributes stored in databases.
63  *
64  * @author David Dearman (dearman@cs.dal.ca)
65  */
66
67 public class JDBCDataConnector extends BaseResolutionPlugIn implements DataConnectorPlugIn {
68
69         private static Logger log = Logger.getLogger(JDBCDataConnector.class.getName());
70         private Hashtable env = new Hashtable();
71         private String searchVal = null;
72         private String aeClassName = null;
73
74         final private static String QueryAtt = "query";
75         final private static String AttributeExtractorAtt = "attributeExtractor";
76         final private static String DBDriverAtt = "dbDriver";
77         final private static String AEInstanceMethodAtt = "instance";
78         final private static String DBSubProtocolAtt = "dbSubProtocol";
79         final private static String DBHostAtt = "dbHost";
80         final private static String DBNameAtt = "dbName";
81         final private static String UserNameAtt = "userName";
82         final private static String PasswordAtt = "password";
83
84         public JDBCDataConnector(Element e) throws ResolutionPlugInException {
85
86                 super(e);
87
88                 NodeList propertiesNode = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Property");
89                 NodeList searchNode = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Search");
90
91                 String propertiesName = null;
92                 String propertiesValue = null;
93
94                 /**
95                  * Gets and sets the search parameter and the attribute extractor
96                  */
97                 searchVal = ((Element) searchNode.item(0)).getAttribute(QueryAtt);
98                 aeClassName = ((Element) searchNode.item(0)).getAttribute(AttributeExtractorAtt);
99
100                 if (searchVal == null || searchVal.equals("")) {
101                         log.error("Search requires a specified query field");
102                         throw new ResolutionPlugInException("mySQLDataConnection requires a \"Search\" specification");
103                 } else {
104                         log.debug("Search Query: (" + searchVal + ")");
105                 }
106
107                 /**
108                  * Assigns the property attribute name/value pairs to a hashtable
109                  */
110                 for (int i = 0; propertiesNode.getLength() > i; i++) {
111                         Element property = (Element) propertiesNode.item(i);
112                         propertiesName = property.getAttribute("name");
113                         propertiesValue = property.getAttribute("value");
114
115                         if (propertiesName != null
116                                 && !propertiesName.equals("")
117                                 && propertiesValue != null
118                                 && !propertiesValue.equals("")) {
119                                 env.put(propertiesName, propertiesValue);
120                                 log.debug("Property: (" + propertiesName + ")");
121                                 log.debug("   Value: (" + propertiesValue + ")");
122                         } else {
123                                 log.error("Property is malformed.");
124                                 throw new ResolutionPlugInException("Property is malformed.");
125                         }
126                 }
127         }
128
129         public Attributes resolve(Principal principal) throws ResolutionPlugInException {
130                 Connection conn = null;
131                 ResultSet rs = null;
132                 ResultSetMetaData rsmd = null;
133                 BasicAttributes attributes = new BasicAttributes();
134                 JDBCAttributeExtractor aeClassObj = null;
135
136                 log.debug("Resolving connector: (" + getId() + ")");
137                 log.debug(getId() + " resolving for principal: (" + principal.getName() + ")");
138
139                 //Replaces %PRINCIPAL% in the query string with its value
140                 log.debug("The query string before coverting %PRINCIPAL%: " + searchVal);
141                 String convertedSearchVal = searchVal.replaceAll("%PRINCIPAL%", principal.getName());
142                 log.debug("The query string after converting %PRINCIPAL%: " + convertedSearchVal);
143
144                 try {
145                         //Loads the database driver
146                         loadDriver((String) env.get(DBDriverAtt));
147                 } catch (ClassNotFoundException e) {
148                         log.error("An ClassNotFoundException occured while loading database driver");
149                         throw new ResolutionPlugInException(
150                                 "An ClassNotFoundException occured while loading database driver: " + e.getMessage());
151                 } catch (IllegalAccessException e) {
152                         log.error("An IllegalAccessException occured while loading database driver");
153                         throw new ResolutionPlugInException(
154                                 "An IllegalAccessException occured while loading database driver: " + e.getMessage());
155                 } catch (InstantiationException e) {
156                         log.error("An InstantionException occured while loading database driver");
157                         throw new ResolutionPlugInException(
158                                 "An InstantiationException occured while loading database driver: " + e.getMessage());
159                 }
160
161                 try {
162                         //Makes the connection to the database
163                         conn =
164                                 connect(
165                                         (String) env.get(DBSubProtocolAtt),
166                                         (String) env.get(DBHostAtt),
167                                         (String) env.get(DBNameAtt),
168                                         (String) env.get(UserNameAtt),
169                                         (String) env.get(PasswordAtt));
170                 } catch (SQLException e) {
171                         log.error("An ERROR occured while connecting to database");
172                         throw new ResolutionPlugInException("An ERROR occured while connecting to the database: " + e.getMessage());
173                 }
174
175                 try {
176                         //Gets the results set for the query
177                         rs = executeQuery(conn, convertedSearchVal);
178                 } catch (SQLException e) {
179                         log.error("An ERROR occured while executing the query");
180                         throw new ResolutionPlugInException("An ERROR occured while executing the query: " + e.getMessage());
181                 }
182
183                 /**
184                  * If the user has supplied their own class for extracting the attributes from the 
185                  * result set, then their class will be run.  A BasicAttributes object is expected as
186                  * the result of the extraction.
187                  *
188                  * If the user has no supplied their own class for extracting the attributes then 
189                  * the default extraction is run, which is specified in DefaultAEAtt.
190                  */
191                 if (aeClassName == null || aeClassName.equals("")) {
192                         aeClassName = DefaultAE.class.getName();
193                 }
194
195                 try {
196                         Class aeClass = Class.forName(aeClassName);
197                         Method aeMethod = aeClass.getMethod(AEInstanceMethodAtt, null);
198
199                         //runs the "instance" method returning and instance of the object
200                         aeClassObj = (JDBCAttributeExtractor) (aeMethod.invoke(null, null));
201                         log.debug("Supplied attributeExtractor class loaded.");
202
203                 } catch (ClassNotFoundException e) {
204                         log.error("The supplied attribute extractor class could not be found");
205                         throw new ResolutionPlugInException(
206                                 "The supplied attribute extractor class could not be found: " + e.getMessage());
207                 } catch (NoSuchMethodException e) {
208                         log.error("The requested method does not exist");
209                         throw new ResolutionPlugInException("The requested method does not exist: " + e.getMessage());
210                 } catch (IllegalAccessException e) {
211                         log.error("Access is not permitted for invoking requested method");
212                         throw new ResolutionPlugInException(
213                                 "Access is not permitted for invoking requested method: " + e.getMessage());
214                 } catch (InvocationTargetException e) {
215                         log.error("An ERROR occured invoking requested method");
216                         throw new ResolutionPlugInException("An ERROR occured involking requested method: " + e.getMessage());
217                 }
218
219                 try {
220                         return aeClassObj.extractAttributes(rs);
221
222                 } catch (JDBCAttributeExtractorException e) {
223                         log.error("An ERROR occured while extracting attributes from result set");
224                         throw new ResolutionPlugInException(
225                                 "An ERROR occured while extracting attributes from result set: " + e.getMessage());
226                 } finally {
227                         try {
228                                 //release result set
229                                 rs.close();
230                                 log.debug("Result set released");
231                         } catch (SQLException e) {
232                                 log.error("An error occured while closing the result set: " + e);
233                                 throw new ResolutionPlugInException("An error occured while closing the result set: " + e);
234                         }
235
236                         try {
237                                 //close the connection
238                                 conn.close();
239                                 log.debug("Connection to database closed");
240                         } catch (SQLException e) {
241                                 log.error("An error occured while closing the database connection: " + e);
242                                 throw new ResolutionPlugInException("An error occured while closing the database connection: " + e);
243                         }
244                 }
245         }
246
247         /** 
248          * Loads the driver used to access the database
249          * @param driver The driver used to access the database
250          * @throws ResolutionPlugInException If there is a failure to load the driver
251          */
252         public void loadDriver(String driver)
253                 throws ClassNotFoundException, IllegalAccessException, InstantiationException {
254                 Class.forName(driver).newInstance();
255                 log.debug("Loading driver: " + driver);
256         }
257
258         /** 
259          * Makes a connection to the database
260          * @param subProtocal Specifies the sub protocal to use when connecting
261          * @param hostName  The host name for the database
262          * @param dbName The database to access
263          * @param userName The username to connect with
264          * @param password The password to connect with
265          * @return Connection objecet
266          * @throws SQLException If there is a failure to make a database connection
267          */
268         public Connection connect(String subProtocol, String hostName, String dbName, String userName, String password)
269                 throws SQLException {
270                 log.debug(
271                         "jdbc:" + subProtocol + "://" + hostName + "/" + dbName + "?user=" + userName + "&password=" + password);
272                 Connection conn =
273                         DriverManager.getConnection("jdbc:" + subProtocol + "://" + hostName + "/" + dbName, userName, password);
274                 log.debug("Connection with database established");
275
276                 return conn;
277         }
278
279         /**
280          * Execute the users query
281          * @param query The query the user wishes to execute
282          * @return The result of the users <code>query</code>
283          * @return null if an error occurs during execution
284          * @throws SQLException If an error occurs while executing the query
285         */
286         public ResultSet executeQuery(Connection conn, String query) throws SQLException {
287                 log.debug("Users Query: " + query);
288                 Statement stmt = conn.createStatement();
289                 return stmt.executeQuery(query);
290         }
291 }
292
293 /**
294  * The default attribute extractor. 
295  */
296
297 class DefaultAE implements JDBCAttributeExtractor {
298         private static DefaultAE _instance = null;
299         private static Logger log = Logger.getLogger(DefaultAE.class.getName());
300
301         // Constructor
302         protected DefaultAE() {
303         }
304
305         // Ensures that only one istance of the class at a time
306         public static DefaultAE instance() {
307                 if (_instance == null)
308                         return new DefaultAE();
309                 else
310                         return _instance;
311         }
312
313         /**
314          * Method of extracting the attributes from the supplied result set.
315          *
316          * @param ResultSet The result set from the query which contains the attributes
317          * @return BasicAttributes as objects containing all the attributes
318          * @throws JDBCAttributeExtractorException If there is a complication in retrieving the attributes
319          */
320         public BasicAttributes extractAttributes(ResultSet rs) throws JDBCAttributeExtractorException {
321                 String columnName = null;
322                 String columnType = null;
323                 int numRows = 0, numColumns = 0;
324                 ResultSetMetaData rsmd = null;
325                 BasicAttributes attributes = new BasicAttributes();
326                 Object columnValue = new Object();
327
328                 log.debug("Using default Attribute Extractor");
329
330                 try {
331                         rs.last();
332                         numRows = rs.getRow();
333                         rs.first();
334                 } catch (SQLException e) {
335                         log.error("An ERROR occured while determining result set row size");
336                         throw new JDBCAttributeExtractorException(
337                                 "An ERROR occured while determining result set row size: " + e.getMessage());
338                 }
339
340                 log.debug("The number of rows returned is: " + numRows);
341
342                 if (numRows > 1)
343                         throw new JDBCAttributeExtractorException("Query returned more than one result set.");
344
345                 try {
346                         rsmd = rs.getMetaData();
347                         numColumns = rsmd.getColumnCount();
348                         log.debug("Number of returned columns: " + numColumns);
349
350                         for (int i = 1; i <= numColumns; i++) {
351                                 columnName = rsmd.getColumnName(i);
352                                 columnType = rsmd.getColumnTypeName(i);
353                                 columnValue = rs.getObject(columnName);
354                                 log.debug(
355                                         "(" + i + ". ColumnType = " + columnType + ") " + columnName + " -> " + columnValue.toString());
356                                 attributes.put(new BasicAttribute(columnName, columnValue));
357                         }
358                 } catch (SQLException e) {
359                         log.error("An ERROR occured while retrieving result set meta data");
360                         throw new JDBCAttributeExtractorException(
361                                 "An ERROR occured while retrieving result set meta data: " + e.getMessage());
362                 }
363
364                 return attributes;
365         }
366 }