8b1d09dbd8a3390a759d251c1ec1cd9eedd2d26a
[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.io.PrintWriter;
29 import java.lang.reflect.Constructor;
30 import java.security.Principal;
31 import java.sql.Blob;
32 import java.sql.Clob;
33 import java.sql.Connection;
34 import java.sql.PreparedStatement;
35 import java.sql.ResultSet;
36 import java.sql.ResultSetMetaData;
37 import java.sql.SQLException;
38 import java.sql.Types;
39 import java.text.SimpleDateFormat;
40 import java.util.ArrayList;
41 import java.util.Iterator;
42 import java.util.Properties;
43
44 import javax.naming.NamingException;
45 import javax.naming.directory.Attribute;
46 import javax.naming.directory.Attributes;
47 import javax.naming.directory.BasicAttribute;
48 import javax.naming.directory.BasicAttributes;
49 import javax.sql.DataSource;
50
51 import org.apache.commons.dbcp.ConnectionFactory;
52 import org.apache.commons.dbcp.DriverManagerConnectionFactory;
53 import org.apache.commons.dbcp.PoolableConnectionFactory;
54 import org.apache.commons.dbcp.PoolingDataSource;
55 import org.apache.commons.pool.impl.GenericObjectPool;
56 import org.apache.commons.pool.impl.StackKeyedObjectPoolFactory;
57 import org.apache.log4j.Logger;
58 import org.apache.log4j.Priority;
59 import org.w3c.dom.Element;
60 import org.w3c.dom.Node;
61 import org.w3c.dom.NodeList;
62
63 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
64 import edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn;
65 import edu.internet2.middleware.shibboleth.aa.attrresolv.Dependencies;
66 import edu.internet2.middleware.shibboleth.aa.attrresolv.ResolutionPlugInException;
67 import edu.internet2.middleware.shibboleth.aa.attrresolv.ResolverAttribute;
68
69 /*
70  * Built at the Canada Institute for Scientific and Technical Information (CISTI 
71  * <ahref="http://www.cisti-icist.nrc-cnrc.gc.ca/">http://www.cisti-icist.nrc-cnrc.gc.ca/</a>, 
72  * the National Research Council Canada 
73  * (NRC <a href="http://www.nrc-cnrc.gc.ca/">http://www.nrc-cnrc.gc.ca/</a>)
74  * by David Dearman, COOP student from Dalhousie University,
75  * under the direction of Glen Newton, Head research (IT)
76  * <ahref="mailto:glen.newton@nrc-cnrc.gc.ca">glen.newton@nrc-cnrc.gc.ca</a>. 
77  */
78
79 /**
80  * Data Connector that uses JDBC to access user attributes stored in databases.
81  *
82  * @author David Dearman (dearman@cs.dal.ca)
83  * @author Walter Hoehn (wassa@columbia.edu)
84  * @author Scott Cantor
85  */
86
87 public class JDBCDataConnector extends BaseDataConnector implements DataConnectorPlugIn {
88
89         private static Logger log = Logger.getLogger(JDBCDataConnector.class.getName());
90         protected String searchVal;
91         protected DataSource dataSource;
92         protected JDBCAttributeExtractor extractor;
93         protected JDBCStatementCreator statementCreator;
94
95         public JDBCDataConnector(Element e) throws ResolutionPlugInException {
96
97                 super(e);
98
99                 //Get the query string
100                 NodeList queryNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Query");
101                 Node tnode = queryNodes.item(0).getFirstChild();
102                 if (tnode != null && tnode.getNodeType() == Node.TEXT_NODE) {
103                         searchVal = tnode.getNodeValue();
104                 }
105                 if (searchVal == null || searchVal.equals("")) {
106                         log.error("Database query must be specified.");
107                         throw new ResolutionPlugInException("Database query must be specified.");
108                 }
109
110                 //Load the supplied JDBC driver
111                 String dbDriverName = e.getAttribute("dbDriver");
112                 if (dbDriverName != null && (!dbDriverName.equals(""))) {
113                         loadDriver(dbDriverName);
114                 }
115
116                 String validationQuery = e.getAttribute("validationQuery");
117                 if (validationQuery == null || validationQuery.equals("")) {
118                         validationQuery = "select 1";
119                 }
120
121                 //Load site-specific implementation classes     
122                 setupAttributeExtractor(
123                         (Element) e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "AttributeExtractor").item(
124                                 0));
125                 setupStatementCreator(
126                         (Element) e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "StatementCreator").item(0));
127         
128         //Load driver properties
129         Properties props = new Properties();
130         NodeList propertiesNode = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Property");
131         for (int i = 0; propertiesNode.getLength() > i; i++) {
132             Element property = (Element) propertiesNode.item(i);
133             String propertiesName = property.getAttribute("name");
134             String propertiesValue = property.getAttribute("value");
135
136             if (propertiesName != null
137                 && !propertiesName.equals("")
138                 && propertiesValue != null
139                 && !propertiesValue.equals("")) {
140                 props.setProperty(propertiesName, propertiesValue);
141                 log.debug("Property: (" + propertiesName + ")");
142                 log.debug("   Value: (" + propertiesValue + ")");
143             } else {
144                 log.error("Property is malformed.");
145                 throw new ResolutionPlugInException("Property is malformed.");
146             }
147         }
148         
149                 //Initialize a pooling Data Source
150                 int maxActive = 0;
151                 int maxIdle = 0;
152         int maxWait = 30;
153                 try {
154                         if (e.getAttributeNode("maxActive") != null) {
155                                 maxActive = Integer.parseInt(e.getAttribute("maxActive"));
156                         }
157                         if (e.getAttributeNode("maxIdle") != null) {
158                                 maxIdle = Integer.parseInt(e.getAttribute("maxIdle"));
159                         }
160             if (e.getAttributeNode("maxWait") != null) {
161                 maxWait = Integer.parseInt(e.getAttribute("maxWait"));
162             }
163                 } catch (NumberFormatException ex) {
164                         log.error("Malformed pooling limits: using defaults.");
165                 }
166                 if (e.getAttribute("dbURL") == null || e.getAttribute("dbURL").equals("")) {
167                         log.error("JDBC connection requires a dbURL property");
168                         throw new ResolutionPlugInException("JDBCDataConnection requires a \"dbURL\" property");
169                 }
170                 setupDataSource(e.getAttribute("dbURL"), props, maxActive, maxIdle, maxWait, validationQuery);
171         }
172
173         /**
174          * Initialize a Pooling Data Source
175          */
176         private void setupDataSource(String dbURL, Properties props, int maxActive, int maxIdle, int maxWait, String validationQuery) throws ResolutionPlugInException {
177
178                 GenericObjectPool objectPool = new GenericObjectPool(null);
179
180                 if (maxActive > 0) {
181                         objectPool.setMaxActive(maxActive);
182                 }
183                 if (maxIdle > 0) {
184                         objectPool.setMaxIdle(maxIdle);
185                 }
186                 if (maxWait > 0) {
187                         objectPool.setMaxWait(1000*maxWait);
188                 }
189
190                 objectPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
191                 objectPool.setTestOnBorrow(true);
192
193                 ConnectionFactory connFactory = null;
194                 PoolableConnectionFactory poolConnFactory = null;
195
196                 try {
197                         connFactory = new DriverManagerConnectionFactory(dbURL, props);
198                         log.debug("Connection factory initialized.");
199                 } catch (Exception ex) {
200                         log.error(
201                                 "Connection factory couldn't be initialized, ensure database URL, username and password are correct.");
202                         throw new ResolutionPlugInException("Connection factory couldn't be initialized: " + ex.getMessage());
203                 }
204
205                 try {
206                         poolConnFactory =
207                         new PoolableConnectionFactory(
208                                 connFactory,
209                                 objectPool,
210                                 new StackKeyedObjectPoolFactory(),
211                                 validationQuery,
212                                 false,
213                                 true);
214                 } catch (Exception ex) {
215                         log.debug("Poolable connection factory error");
216                 }
217
218                 dataSource = new PoolingDataSource(objectPool);
219                 log.info("Data Source initialized.");
220                 try {
221                         dataSource.setLogWriter(
222                                 new Log4jPrintWriter(Logger.getLogger(JDBCDataConnector.class.getName() + ".Pool"), Priority.DEBUG));
223                 } catch (SQLException e) {
224                         log.error("Coudn't setup logger for database connection pool.");
225                 }
226         }
227
228         /**
229          * Instantiate an Attribute Extractor, using the default if none was configured
230          */
231         private void setupAttributeExtractor(Element config) throws ResolutionPlugInException {
232
233                 String className = null;
234                 if (config != null) {
235                         className = config.getAttribute("class");
236                 }
237                 if (className == null || className.equals("")) {
238                         log.debug("Using default Attribute Extractor.");
239                         className = DefaultAE.class.getName();
240                 }
241                 try {
242                         Class aeClass = Class.forName(className);
243                         extractor = (JDBCAttributeExtractor) aeClass.newInstance();
244                         log.debug("Attribute Extractor implementation loaded.");
245
246                 } catch (ClassNotFoundException e) {
247                         log.error("The supplied Attribute Extractor class could not be found: " + e);
248                         throw new ResolutionPlugInException(
249                                 "The supplied Attribute Extractor class could not be found: " + e.getMessage());
250                 } catch (Exception e) {
251                         log.error("Unable to instantiate Attribute Extractor implementation: " + e);
252                         throw new ResolutionPlugInException(
253                                 "Unable to instantiate Attribute Extractor implementation: " + e.getMessage());
254                 }
255         }
256
257         /**
258          * Instantiate a Statement Creator, using the default if none was configured
259          */
260         private void setupStatementCreator(Element config) throws ResolutionPlugInException {
261
262                 String scClassName = null;
263                 if (config != null) {
264                         scClassName = config.getAttribute("class");
265                 }
266                 if (scClassName == null || scClassName.equals("")) {
267                         log.debug("Using default Statement Creator.");
268                         scClassName = DefaultStatementCreator.class.getName();
269                 }
270                 try {
271                         Class scClass = Class.forName(scClassName);
272
273                         Class[] params = new Class[1];
274                         params[0] = Class.forName("org.w3c.dom.Element");
275                         try {
276                                 Constructor implementorConstructor = scClass.getConstructor(params);
277                                 Object[] args = new Object[1];
278                                 args[0] = config;
279                                 log.debug("Initializing Statement Creator of type (" + scClass.getName() + ").");
280                                 statementCreator = (JDBCStatementCreator) implementorConstructor.newInstance(args);
281                         } catch (NoSuchMethodException nsme) {
282                                 log.debug(
283                                         "Implementation constructor does have a parameterized constructor, attempting to load default.");
284                                 statementCreator = (JDBCStatementCreator) scClass.newInstance();
285                         }
286                         log.debug("Statement Creator implementation loaded.");
287
288                 } catch (ClassNotFoundException e) {
289                         log.error("The supplied Statement Creator class could not be found: " + e);
290                         throw new ResolutionPlugInException(
291                                 "The supplied Statement Creator class could not be found: " + e.getMessage());
292                 } catch (Exception e) {
293                         log.error("Unable to instantiate Statement Creator implementation: " + e);
294                         throw new ResolutionPlugInException(
295                                 "Unable to instantiate Statement Creator implementation: " + e.getMessage());
296                 }
297         }
298
299         public Attributes resolve(Principal principal, String requester, Dependencies depends)
300                 throws ResolutionPlugInException {
301
302                 log.debug("Resolving connector: (" + getId() + ")");
303
304                 //Retrieve a connection from the connection pool
305                 Connection conn = null;
306                 try {
307                         conn = dataSource.getConnection();
308                         log.debug("Connection retrieved from pool");
309                 } catch (Exception e) {
310                         log.error("Unable to fetch a connection from the pool");
311                         throw new ResolutionPlugInException("Unable to fetch a connection from the pool: " + e.getMessage());
312                 }
313                 if (conn == null) {
314                         log.error("Pool didn't return a propertly initialized connection.");
315                         throw new ResolutionPlugInException("Pool didn't return a properly initialized connection.");
316                 }
317
318                 //Setup and execute a (pooled) prepared statement
319                 ResultSet rs = null;
320                 PreparedStatement preparedStatement = null;
321                 try {
322                         preparedStatement = conn.prepareStatement(searchVal);
323                         statementCreator.create(preparedStatement, principal, requester, depends);
324                         rs = preparedStatement.executeQuery();
325                         if (!rs.next()) {
326                                 return new BasicAttributes();
327                         }
328             return extractor.extractAttributes(rs);
329                 } catch (JDBCStatementCreatorException e) {
330                         log.error("An ERROR occured while constructing the query");
331                         throw new ResolutionPlugInException("An ERROR occured while constructing the query: " + e.getMessage());
332         } catch (JDBCAttributeExtractorException e) {
333             log.error("An ERROR occured while extracting attributes from result set");
334             throw new ResolutionPlugInException("An ERROR occured while extracting attributes from result set: " + e.getMessage());
335                 } catch (SQLException e) {
336                         log.error("An ERROR occured while executing the query");
337                         throw new ResolutionPlugInException("An ERROR occured while executing the query: " + e.getMessage());
338         } finally {
339             Exception e_save = null;
340             try {
341                 if (preparedStatement != null) {
342                     preparedStatement.close();
343                 }
344             } catch (SQLException e) {
345                 log.error("An error occured while closing the prepared statement: " + e.getMessage());
346                 e_save = e;
347             }
348             try {
349                 if (rs != null) {
350                     rs.close();
351                 }
352             } catch (SQLException e) {
353                 log.error("An error occured while closing the result set: " + e.getMessage());
354                 e_save = e;
355             }
356             try {
357                 conn.close();
358             } catch (SQLException e) {
359                 log.error("An error occured while closing the database connection: " + e.getMessage());
360                 e_save = e;
361             }
362             if (e_save != null) {
363                 throw new ResolutionPlugInException("An error occured while closing database objects:" + e_save.getMessage());
364             }
365         }
366         }
367
368         /** 
369          * Loads the driver used to access the database
370          * @param driver The driver used to access the database
371          * @throws ResolutionPlugInException If there is a failure to load the driver
372          */
373         public void loadDriver(String driver) throws ResolutionPlugInException {
374                 try {
375                         Class.forName(driver).newInstance();
376                         log.debug("Loading JDBC driver: " + driver);
377                 } catch (Exception e) {
378                         log.error("An error loading database driver: " + e);
379                         throw new ResolutionPlugInException(
380                                 "An IllegalAccessException occured while loading database driver: " + e.getMessage());
381                 }
382                 log.debug("Driver loaded.");
383         }
384
385         private class Log4jPrintWriter extends PrintWriter {
386
387                 private Priority level;
388                 private Logger logger;
389                 private StringBuffer text = new StringBuffer("");
390
391                 private Log4jPrintWriter(Logger logger, org.apache.log4j.Priority level) {
392                         super(System.err);
393                         this.level = level;
394                         this.logger = logger;
395                 }
396
397                 public void close() {
398                         flush();
399                 }
400
401                 public void flush() {
402                         if (!text.toString().equals("")) {
403                                 logger.log(level, text.toString());
404                                 text.setLength(0);
405                         }
406                 }
407
408                 public void print(boolean b) {
409                         text.append(b);
410                 }
411
412                 public void print(char c) {
413                         text.append(c);
414                 }
415
416                 public void print(char[] s) {
417                         text.append(s);
418                 }
419
420                 public void print(double d) {
421                         text.append(d);
422                 }
423
424                 public void print(float f) {
425                         text.append(f);
426                 }
427
428                 public void print(int i) {
429                         text.append(i);
430                 }
431
432                 public void print(long l) {
433                         text.append(l);
434                 }
435
436                 public void print(Object obj) {
437                         text.append(obj);
438                 }
439
440                 public void print(String s) {
441                         text.append(s);
442                 }
443
444                 public void println() {
445                         if (!text.toString().equals("")) {
446                                 logger.log(level, text.toString());
447                                 text.setLength(0);
448                         }
449                 }
450
451                 public void println(boolean x) {
452                         text.append(x);
453                         logger.log(level, text.toString());
454                         text.setLength(0);
455                 }
456
457                 public void println(char x) {
458                         text.append(x);
459                         logger.log(level, text.toString());
460                         text.setLength(0);
461                 }
462
463                 public void println(char[] x) {
464                         text.append(x);
465                         logger.log(level, text.toString());
466                         text.setLength(0);
467                 }
468
469                 public void println(double x) {
470                         text.append(x);
471                         logger.log(level, text.toString());
472                         text.setLength(0);
473                 }
474
475                 public void println(float x) {
476                         text.append(x);
477                         logger.log(level, text.toString());
478                         text.setLength(0);
479                 }
480
481                 public void println(int x) {
482                         text.append(x);
483                         logger.log(level, text.toString());
484                         text.setLength(0);
485                 }
486
487                 public void println(long x) {
488                         text.append(x);
489                         logger.log(level, text.toString());
490                         text.setLength(0);
491                 }
492
493                 public void println(Object x) {
494                         text.append(x);
495                         logger.log(level, text.toString());
496                         text.setLength(0);
497                 }
498
499                 public void println(String x) {
500                         text.append(x);
501                         logger.log(level, text.toString());
502                         text.setLength(0);
503                 }
504         }
505 }
506
507 /**
508  * The default attribute extractor. 
509  */
510 class DefaultAE implements JDBCAttributeExtractor {
511
512         private static Logger log = Logger.getLogger(DefaultAE.class.getName());
513
514         /**
515          * Method of extracting the attributes from the supplied result set.
516          *
517          * @param ResultSet The result set from the query which contains the attributes
518          * @return BasicAttributes as objects containing all the attributes
519          * @throws JDBCAttributeExtractorException If there is a complication in retrieving the attributes
520          */
521         public BasicAttributes extractAttributes(ResultSet rs) throws JDBCAttributeExtractorException {
522                 BasicAttributes attributes = new BasicAttributes();
523         int row = 0;
524         
525                 try {
526             // Get metadata about result set.
527             ResultSetMetaData rsmd = rs.getMetaData();
528             int numColumns = rsmd.getColumnCount();
529             log.debug("Number of returned columns: " + numColumns);
530
531             do {
532                 for (int i = 1; i <= numColumns; i++) {
533                     String columnName = rsmd.getColumnName(i);
534                     Object columnValue = rs.getObject(columnName);
535                     if (log.isDebugEnabled()) {
536                         log.debug(
537                             "("
538                                 + i
539                                 + ". ColumnType = " + rsmd.getColumnTypeName(i)
540                                 + ") "
541                                 + columnName
542                                 + " -> "
543                                 + (columnValue != null ? columnValue.toString() : "(null)"));
544                     }
545                     if (row == 0) {
546                         BasicAttribute ba = new BasicAttribute(columnName, true);
547                         ba.add(row,columnValue);
548                         attributes.put(ba);
549                     }
550                     else {
551                         attributes.get(columnName).add(row,columnValue);
552                     }
553                 }
554                 row++;
555             } while (rs.next());
556                 } catch (SQLException e) {
557                         log.error("An ERROR occured while processing result set");
558                         throw new JDBCAttributeExtractorException(
559                                 "An ERROR occured while processing result set: " + e.getMessage());
560                 }
561
562                 return attributes;
563         }
564 }
565
566 class DefaultStatementCreator implements JDBCStatementCreator {
567
568         private static Logger log = Logger.getLogger(DefaultStatementCreator.class.getName());
569
570         public void create(
571                 PreparedStatement preparedStatement,
572                 Principal principal,
573                 String requester,
574                 Dependencies depends)
575                 throws JDBCStatementCreatorException {
576
577                 try {
578                         log.debug("Creating prepared statement.  Substituting principal: (" + principal.getName() + ")");
579                         preparedStatement.setString(1, principal.getName());
580             //Tried using ParameterMetaData to determine param count, but it fails, so...
581             try {
582                 int i=2;
583                 while (true) {
584                     preparedStatement.setString(i++, principal.getName());
585                 }
586             } catch (SQLException e) {
587                 //Ignore any additional exceptions, assume parameters simply don't exist.
588             }
589                 } catch (SQLException e) {
590                         log.error("Encountered an error while creating prepared statement: " + e);
591                         throw new JDBCStatementCreatorException(
592                                 "Encountered an error while creating prepared statement: " + e.getMessage());
593                 }
594         }
595 }
596
597 class DependencyStatementCreator implements JDBCStatementCreator {
598
599         private static Logger log = Logger.getLogger(DependencyStatementCreator.class.getName());
600         private ArrayList parameters = new ArrayList();
601
602         public DependencyStatementCreator(Element conf) throws JDBCStatementCreatorException {
603
604                 NodeList nodes = conf.getElementsByTagName("Parameter");
605                 for (int i = 0; i < nodes.getLength(); i++) {
606                         Element parameter = (Element) nodes.item(i);
607                         String type = "String";
608                         if (parameter.getAttribute("type") != null && (!parameter.getAttribute("type").equals(""))) {
609                                 type = parameter.getAttribute("type");
610                         }
611
612                         if (parameter.getAttribute("attributeName") == null
613                                 || parameter.getAttribute("attributeName").equals("")) {
614                                 log.error("Statement Creator Parameter must reference an attribute by name.");
615                                 throw new JDBCStatementCreatorException("Statement Creator Parameter must reference an attribute by name.");
616                         }
617
618                         if (parameter.getAttribute("connectorId") != null && (!parameter.getAttribute("connectorId").equals(""))) {
619                                 parameters.add(
620                                         new Parameter(
621                                                 type,
622                                                 parameter.getAttribute("attributeName"),
623                                                 parameter.getAttribute("connectorId")));
624                         } else {
625                                 parameters.add(new Parameter(type, parameter.getAttribute("attributeName")));
626
627                         }
628
629                         if (parameter.getAttribute("nullMissing") != null && (!parameter.getAttribute("nullMissing").equals(""))) {
630                                 if (parameter.getAttribute("nullMissing").equalsIgnoreCase("FALSE")) {
631                                         ((Parameter) parameters.get(i)).setNullMissing(false);
632                                 }
633                         }
634                 }
635                 log.debug("Parameters configured: " + parameters.size());
636         }
637
638         public void create(
639                 PreparedStatement preparedStatement,
640                 Principal principal,
641                 String requester,
642                 Dependencies depends)
643                 throws JDBCStatementCreatorException {
644
645                 try {
646                         log.debug("Creating prepared statement.  Substituting values from dependencies.");
647                         for (int i = 0; i < parameters.size(); i++) {
648                                 ((Parameter) parameters.get(i)).setParameterValue(preparedStatement, i + 1, depends);
649                         }
650
651                 } catch (Exception e) {
652                         log.error("Encountered an error while creating prepared statement: " + e);
653                         throw new JDBCStatementCreatorException(
654                                 "Encountered an error while creating prepared statement: " + e.getMessage());
655                 }
656         }
657
658         protected class Parameter {
659                 private String type;
660                 private String attributeName;
661                 private boolean referencesConnector = false;
662                 private String connectorId;
663                 private boolean nullMissing = true;
664
665                 protected Parameter(String type, String attributeName) throws JDBCStatementCreatorException {
666                         if ((!type.equalsIgnoreCase("String"))
667                                 && (!type.equalsIgnoreCase("Integer"))
668                                 && (!type.equalsIgnoreCase("Byte"))
669                                 && (!type.equalsIgnoreCase("Double"))
670                                 && (!type.equalsIgnoreCase("Float"))
671                                 && (!type.equalsIgnoreCase("Long"))
672                                 && (!type.equalsIgnoreCase("Short"))
673                                 && (!type.equalsIgnoreCase("Boolean"))
674                                 && (!type.equalsIgnoreCase("Date"))
675                                 && (!type.equalsIgnoreCase("Blob"))
676                                 && (!type.equalsIgnoreCase("Clob"))) {
677                                 log.error("Unsupported type configured for Statement Creator Parameter.");
678                                 throw new JDBCStatementCreatorException("Unsupported type on Statement Creator Parameter.");
679                         }
680                         this.type = type;
681                         this.attributeName = attributeName;
682                 }
683
684                 protected Parameter(String type, String attributeName, String connectorId)
685                         throws JDBCStatementCreatorException {
686                         this(type, attributeName);
687                         referencesConnector = true;
688                         this.connectorId = connectorId;
689
690                 }
691         
692         protected int getSQLType() {
693             if (type.equalsIgnoreCase("String")) {
694                 return Types.VARCHAR;
695             } else if (type.equalsIgnoreCase("Integer")) {
696                 return Types.INTEGER;
697             } else if (type.equalsIgnoreCase("Byte")) {
698                 return Types.TINYINT;
699             } else if (type.equalsIgnoreCase("Double")) {
700                 return Types.DOUBLE;
701             } else if (type.equalsIgnoreCase("Float")) {
702                 return Types.FLOAT;
703             } else if (type.equalsIgnoreCase("Long")) {
704                 return Types.INTEGER;
705             } else if (type.equalsIgnoreCase("Short")) {
706                 return Types.SMALLINT;
707             } else if (type.equalsIgnoreCase("Boolean")) {
708                 return Types.BOOLEAN;
709             } else if (type.equalsIgnoreCase("Date")) {
710                 return Types.DATE;
711             } else if (type.equalsIgnoreCase("Blob")) {
712                 return Types.BLOB;
713             } else if (type.equalsIgnoreCase("Clob")) {
714                 return Types.CLOB;
715             } else {
716                 return Types.VARCHAR;
717             }
718         }
719
720                 protected void setParameterValue(PreparedStatement preparedStatement, int valueIndex, Dependencies depends)
721                         throws JDBCStatementCreatorException {
722
723                         //handle values from DataConnectors
724                         if (referencesConnector) {
725                                 Attributes attributes = depends.getConnectorResolution(connectorId);
726                                 if (attributes == null) {
727                                         log.error(
728                                                 "Statement Creator misconfiguration: Connector ("
729                                                         + connectorId
730                                                         + ") is not a dependency of this JDBCDataConnector.");
731                                         throw new JDBCStatementCreatorException(
732                                                 "Statement Creator misconfiguration: Connector ("
733                                                         + connectorId
734                                                         + ") is not a dependency of this JDBCDataConnector.");
735                                 }
736
737                                 Attribute attribute = attributes.get(attributeName);
738                                 if (attribute == null || attribute.size() < 1) {
739                                         if (nullMissing) {
740                                                 try {
741                                                         preparedStatement.setNull(valueIndex, getSQLType());
742                                                         return;
743                                                 } catch (SQLException e) {
744                                                         log.error(
745                                                                 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
746                                                 }
747                                         }
748                                         log.error("Cannot parameterize prepared statement: missing dependency value.");
749                                         throw new JDBCStatementCreatorException("Cannot parameterize prepared statement: missing dependency value.");
750                                 }
751
752                                 if (attribute.size() > 1) {
753                                         log.error("Statement Creator encountered a multivalued dependent attribute.");
754                                         throw new JDBCStatementCreatorException("Statement Creator encountered a multivalued dependent attribute.");
755                                 }
756
757                                 try {
758                                         setSpecificParameter(preparedStatement, valueIndex, attribute.get());
759                                         return;
760                                 } catch (NamingException e) {
761                                         log.error(
762                                                 "Statement Creator encountered an error while extracting attributes from a Data Conector: "
763                                                         + e);
764                                         throw new JDBCStatementCreatorException(
765                                                 "Statement Creator encountered an error while extracting attributes from a Data Conector: "
766                                                         + e.getMessage());
767                                 }
768                         }
769
770                         //handle values from AttributeDefinitons
771                         ResolverAttribute attribute = depends.getAttributeResolution(attributeName);
772                         if (attribute != null) {
773                                 Iterator iterator = attribute.getValues();
774                                 if (iterator.hasNext()) {
775                                         setSpecificParameter(preparedStatement, valueIndex, iterator.next());
776                                         if (iterator.hasNext()) {
777                                                 log.error("Statement Creator encountered a multivalued dependent attribute.");
778                                                 throw new JDBCStatementCreatorException("Statement Creator encountered a multivalued dependent attribute.");
779                                         }
780                                         return;
781                                 }
782                         }
783                         if (nullMissing) {
784                                 try {
785                                         preparedStatement.setNull(valueIndex, getSQLType());
786                                         return;
787                                 } catch (SQLException e) {
788                                         log.error(
789                                                 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
790                                 }
791                         }
792                         log.error("Cannot parameterize prepared statement: missing dependency value.");
793                         throw new JDBCStatementCreatorException("Cannot parameterize prepared statement: missing dependency value.");
794                 }
795
796                 protected void setNullMissing(boolean nullMissing) {
797                         this.nullMissing = nullMissing;
798                 }
799
800                 private void setSpecificParameter(PreparedStatement preparedStatement, int valueIndex, Object object)
801                         throws JDBCStatementCreatorException {
802
803                         if (object == null) {
804                                 try {
805                                         preparedStatement.setNull(valueIndex, getSQLType());
806                                         return;
807                                 } catch (SQLException e) {
808                                         log.error(
809                                                 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
810                                         throw new JDBCStatementCreatorException("Encountered a problem while attempting to convert missing attribute value to null parameter.");
811                                 }
812                         } else if (type.equalsIgnoreCase("String")) {
813                                 setString(preparedStatement, valueIndex, object);
814                         } else if (type.equalsIgnoreCase("Integer")) {
815                                 setInteger(preparedStatement, valueIndex, object);
816                         } else if (type.equalsIgnoreCase("Byte")) {
817                                 setByte(preparedStatement, valueIndex, object);
818                         } else if (type.equalsIgnoreCase("Double")) {
819                                 setDouble(preparedStatement, valueIndex, object);
820                         } else if (type.equalsIgnoreCase("Float")) {
821                                 setFloat(preparedStatement, valueIndex, object);
822                         } else if (type.equalsIgnoreCase("Long")) {
823                                 setLong(preparedStatement, valueIndex, object);
824                         } else if (type.equalsIgnoreCase("Short")) {
825                                 setShort(preparedStatement, valueIndex, object);
826                         } else if (type.equalsIgnoreCase("Boolean")) {
827                                 setBoolean(preparedStatement, valueIndex, object);
828                         } else if (type.equalsIgnoreCase("Date")) {
829                                 setDate(preparedStatement, valueIndex, object);
830                         } else if (type.equalsIgnoreCase("Blob")) {
831                                 setBlob(preparedStatement, valueIndex, object);
832                         } else if (type.equalsIgnoreCase("Clob")) {
833                                 setClob(preparedStatement, valueIndex, object);
834                         } else {
835                                 setString(preparedStatement, valueIndex, object);
836                         }
837                 }
838
839                 private void setClob(PreparedStatement preparedStatement, int valueIndex, Object object)
840                         throws JDBCStatementCreatorException {
841                         if (object instanceof Clob) {
842                                 try {
843                                         preparedStatement.setClob(valueIndex, (Clob) object);
844                                         return;
845                                 } catch (SQLException e) {
846                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
847                                         throw new JDBCStatementCreatorException(
848                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
849                                 }
850                         }
851                         log.error("Encountered a dependency with an invalid java type.");
852                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
853                 }
854
855                 private void setBlob(PreparedStatement preparedStatement, int valueIndex, Object object)
856                         throws JDBCStatementCreatorException {
857                         if (object instanceof Blob) {
858                                 try {
859                                         preparedStatement.setBlob(valueIndex, (Blob) object);
860                                         return;
861                                 } catch (SQLException e) {
862                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
863                                         throw new JDBCStatementCreatorException(
864                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
865                                 }
866                         }
867                         log.error("Encountered a dependency with an invalid java type.");
868                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
869                 }
870
871                 private void setDate(PreparedStatement preparedStatement, int valueIndex, Object object)
872                         throws JDBCStatementCreatorException {
873
874                         if (object instanceof java.sql.Date) {
875                                 try {
876                                         preparedStatement.setDate(valueIndex, (java.sql.Date) object);
877                                         return;
878                                 } catch (SQLException e) {
879                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
880                                         throw new JDBCStatementCreatorException(
881                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
882                                 }
883                         } else if (object instanceof java.util.Date) {
884                                 try {
885                                         //If you want to be frustrated by the java class library, look no further...
886                                         preparedStatement.setDate(valueIndex, new java.sql.Date(((java.util.Date) object).getTime()));
887                                         return;
888                                 } catch (SQLException e) {
889                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
890                                         throw new JDBCStatementCreatorException(
891                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
892                                 }
893                         } else if (object instanceof Long) {
894                                 try {
895                                         preparedStatement.setDate(valueIndex, new java.sql.Date(((Long) object).longValue()));
896                                         return;
897                                 } catch (SQLException e) {
898                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
899                                         throw new JDBCStatementCreatorException(
900                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
901                                 }
902                         } else if (object instanceof String) {
903                                 try {
904                                         preparedStatement.setDate(
905                                                 valueIndex,
906                                                 new java.sql.Date(new SimpleDateFormat().parse((String) object).getTime()));
907                                         return;
908                                 } catch (Exception e) {
909                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
910                                         throw new JDBCStatementCreatorException(
911                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
912                                 }
913                         }
914                         log.error("Encountered a dependency with an invalid java type.");
915                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
916                 }
917
918                 private void setBoolean(PreparedStatement preparedStatement, int valueIndex, Object object)
919                         throws JDBCStatementCreatorException {
920                         if (object instanceof Boolean) {
921                                 try {
922                                         preparedStatement.setBoolean(valueIndex, ((Boolean) object).booleanValue());
923                                         return;
924                                 } catch (SQLException e) {
925                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
926                                         throw new JDBCStatementCreatorException(
927                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
928                                 }
929                         } else if (object instanceof String) {
930                                 try {
931                                         preparedStatement.setBoolean(valueIndex, new Boolean((String) object).booleanValue());
932                                         return;
933                                 } catch (Exception e) {
934                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
935                                         throw new JDBCStatementCreatorException(
936                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
937                                 }
938                         }
939                         log.error("Encountered a dependency with an invalid java type.");
940                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
941                 }
942
943                 private void setShort(PreparedStatement preparedStatement, int valueIndex, Object object)
944                         throws JDBCStatementCreatorException {
945                         if (object instanceof Boolean) {
946                                 try {
947                                         preparedStatement.setShort(valueIndex, ((Short) object).shortValue());
948                                         return;
949                                 } catch (SQLException e) {
950                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
951                                         throw new JDBCStatementCreatorException(
952                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
953                                 }
954                         } else if (object instanceof String) {
955                                 try {
956                                         preparedStatement.setShort(valueIndex, new Short((String) object).shortValue());
957                                         return;
958                                 } catch (Exception e) {
959                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
960                                         throw new JDBCStatementCreatorException(
961                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
962                                 }
963                         }
964                         log.error("Encountered a dependency with an invalid java type.");
965                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
966                 }
967
968                 private void setLong(PreparedStatement preparedStatement, int valueIndex, Object object)
969                         throws JDBCStatementCreatorException {
970                         if (object instanceof Long || object instanceof Integer || object instanceof Short) {
971                                 try {
972                                         preparedStatement.setLong(valueIndex, ((Number) object).longValue());
973                                         return;
974                                 } catch (SQLException e) {
975                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
976                                         throw new JDBCStatementCreatorException(
977                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
978                                 }
979                         } else if (object instanceof String) {
980                                 try {
981                                         preparedStatement.setLong(valueIndex, new Long((String) object).longValue());
982                                         return;
983                                 } catch (Exception e) {
984                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
985                                         throw new JDBCStatementCreatorException(
986                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
987                                 }
988                         }
989                         log.error("Encountered a dependency with an invalid java type.");
990                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
991                 }
992
993                 private void setFloat(PreparedStatement preparedStatement, int valueIndex, Object object)
994                         throws JDBCStatementCreatorException {
995                         if (object instanceof Float) {
996                                 try {
997                                         preparedStatement.setFloat(valueIndex, ((Float) object).floatValue());
998                                         return;
999                                 } catch (SQLException e) {
1000                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1001                                         throw new JDBCStatementCreatorException(
1002                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1003                                 }
1004                         } else if (object instanceof String) {
1005                                 try {
1006                                         preparedStatement.setFloat(valueIndex, new Float((String) object).floatValue());
1007                                         return;
1008                                 } catch (Exception e) {
1009                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1010                                         throw new JDBCStatementCreatorException(
1011                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1012                                 }
1013                         }
1014                         log.error("Encountered a dependency with an invalid java type.");
1015                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1016                 }
1017
1018                 private void setDouble(PreparedStatement preparedStatement, int valueIndex, Object object)
1019                         throws JDBCStatementCreatorException {
1020                         if (object instanceof Double || object instanceof Float) {
1021                                 try {
1022                                         preparedStatement.setDouble(valueIndex, ((Number) object).doubleValue());
1023                                         return;
1024                                 } catch (SQLException e) {
1025                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1026                                         throw new JDBCStatementCreatorException(
1027                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1028                                 }
1029                         } else if (object instanceof String) {
1030                                 try {
1031                                         preparedStatement.setDouble(valueIndex, new Double((String) object).doubleValue());
1032                                         return;
1033                                 } catch (Exception e) {
1034                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1035                                         throw new JDBCStatementCreatorException(
1036                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1037                                 }
1038                         }
1039                         log.error("Encountered a dependency with an invalid java type.");
1040                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1041                 }
1042
1043                 private void setByte(PreparedStatement preparedStatement, int valueIndex, Object object)
1044                         throws JDBCStatementCreatorException {
1045                         if (object instanceof Byte) {
1046                                 try {
1047                                         preparedStatement.setByte(valueIndex, ((Byte) object).byteValue());
1048                                         return;
1049                                 } catch (SQLException e) {
1050                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1051                                         throw new JDBCStatementCreatorException(
1052                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1053                                 }
1054                         } else if (object instanceof String) {
1055                                 try {
1056                                         preparedStatement.setByte(valueIndex, new Byte((String) object).byteValue());
1057                                         return;
1058                                 } catch (Exception e) {
1059                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1060                                         throw new JDBCStatementCreatorException(
1061                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1062                                 }
1063                         }
1064                         log.error("Encountered a dependency with an invalid java type.");
1065                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1066                 }
1067
1068                 private void setInteger(PreparedStatement preparedStatement, int valueIndex, Object object)
1069                         throws JDBCStatementCreatorException {
1070                         if (object instanceof Integer || object instanceof Short) {
1071                                 try {
1072                                         preparedStatement.setInt(valueIndex, ((Number) object).intValue());
1073                                         return;
1074                                 } catch (SQLException e) {
1075                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1076                                         throw new JDBCStatementCreatorException(
1077                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1078                                 }
1079                         } else if (object instanceof String) {
1080                                 try {
1081                                         preparedStatement.setInt(valueIndex, new Integer((String) object).intValue());
1082                                         return;
1083                                 } catch (Exception e) {
1084                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1085                                         throw new JDBCStatementCreatorException(
1086                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1087                                 }
1088                         }
1089                         log.error("Encountered a dependency with an invalid java type.");
1090                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1091                 }
1092
1093                 private void setString(PreparedStatement preparedStatement, int valueIndex, Object object)
1094                         throws JDBCStatementCreatorException {
1095                         if (object instanceof String) {
1096                                 try {
1097                                         preparedStatement.setString(valueIndex, (String) object);
1098                                         return;
1099                                 } catch (SQLException e) {
1100                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1101                                         throw new JDBCStatementCreatorException(
1102                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1103                                 }
1104                         }
1105                         log.error("Encountered a dependency with an invalid java type.");
1106                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1107                 }
1108         }
1109 }