Substitute principal multiple times.
[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 BaseResolutionPlugIn 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     protected String failover = null;
95
96         public JDBCDataConnector(Element e) throws ResolutionPlugInException {
97
98                 super(e);
99
100         NodeList failoverNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "FailoverDependency");
101         if (failoverNodes.getLength() > 0) {
102             failover = ((Element)failoverNodes.item(0)).getAttribute("requires");
103         }
104                 //Get the query string
105                 NodeList queryNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Query");
106                 Node tnode = queryNodes.item(0).getFirstChild();
107                 if (tnode != null && tnode.getNodeType() == Node.TEXT_NODE) {
108                         searchVal = tnode.getNodeValue();
109                 }
110                 if (searchVal == null || searchVal.equals("")) {
111                         log.error("Database query must be specified.");
112                         throw new ResolutionPlugInException("Database query must be specified.");
113                 }
114
115                 //Load the supplied JDBC driver
116                 String dbDriverName = e.getAttribute("dbDriver");
117                 if (dbDriverName != null && (!dbDriverName.equals(""))) {
118                         loadDriver(dbDriverName);
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                 try {
153                         if (e.getAttributeNode("maxActive") != null) {
154                                 maxActive = Integer.parseInt(e.getAttribute("maxActive"));
155                         }
156                         if (e.getAttributeNode("maxIdle") != null) {
157                                 maxIdle = Integer.parseInt(e.getAttribute("maxIdle"));
158                         }
159                 } catch (NumberFormatException ex) {
160                         log.error("Malformed pooling limits: using defaults.");
161                 }
162                 if (e.getAttribute("dbURL") == null || e.getAttribute("dbURL").equals("")) {
163                         log.error("JDBC connection requires a dbURL property");
164                         throw new ResolutionPlugInException("JDBCDataConnection requires a \"dbURL\" property");
165                 }
166                 setupDataSource(e.getAttribute("dbURL"), props, maxActive, maxIdle);
167         }
168
169         /**
170          * Initialize a Pooling Data Source
171          */
172         private void setupDataSource(String dbURL, Properties props, int maxActive, int maxIdle) throws ResolutionPlugInException {
173
174                 GenericObjectPool objectPool = new GenericObjectPool(null);
175
176                 if (maxActive > 0) {
177                         objectPool.setMaxActive(maxActive);
178                 }
179                 if (maxIdle > 0) {
180                         objectPool.setMaxIdle(maxIdle);
181                 }
182
183                 objectPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
184
185                 ConnectionFactory connFactory = null;
186                 PoolableConnectionFactory poolConnFactory = null;
187
188                 try {
189                         connFactory = new DriverManagerConnectionFactory(dbURL, props);
190                         log.debug("Connection factory initialized.");
191                 } catch (Exception ex) {
192                         log.error(
193                                 "Connection factory couldn't be initialized, ensure database URL, username and password are correct.");
194                         throw new ResolutionPlugInException("Connection factory couldn't be initialized: " + ex.getMessage());
195                 }
196
197                 try {
198                         poolConnFactory =
199                         new PoolableConnectionFactory(
200                                 connFactory,
201                                 objectPool,
202                                 new StackKeyedObjectPoolFactory(),
203                                 null,
204                                 false,
205                                         true);
206                 } catch (Exception ex) {
207                         log.debug("Poolable connection factory error");
208                 }
209
210                 dataSource = new PoolingDataSource(objectPool);
211                 log.info("Data Source initialized.");
212                 try {
213                         dataSource.setLogWriter(
214                                 new Log4jPrintWriter(Logger.getLogger(JDBCDataConnector.class.getName() + ".Pool"), Priority.DEBUG));
215                 } catch (SQLException e) {
216                         log.error("Coudn't setup logger for database connection pool.");
217                 }
218         }
219
220         /**
221          * Instantiate an Attribute Extractor, using the default if none was configured
222          */
223         private void setupAttributeExtractor(Element config) throws ResolutionPlugInException {
224
225                 String className = null;
226                 if (config != null) {
227                         className = config.getAttribute("class");
228                 }
229                 if (className == null || className.equals("")) {
230                         log.debug("Using default Attribute Extractor.");
231                         className = DefaultAE.class.getName();
232                 }
233                 try {
234                         Class aeClass = Class.forName(className);
235                         extractor = (JDBCAttributeExtractor) aeClass.newInstance();
236                         log.debug("Attribute Extractor implementation loaded.");
237
238                 } catch (ClassNotFoundException e) {
239                         log.error("The supplied Attribute Extractor class could not be found: " + e);
240                         throw new ResolutionPlugInException(
241                                 "The supplied Attribute Extractor class could not be found: " + e.getMessage());
242                 } catch (Exception e) {
243                         log.error("Unable to instantiate Attribute Extractor implementation: " + e);
244                         throw new ResolutionPlugInException(
245                                 "Unable to instantiate Attribute Extractor implementation: " + e.getMessage());
246                 }
247         }
248
249         /**
250          * Instantiate a Statement Creator, using the default if none was configured
251          */
252         private void setupStatementCreator(Element config) throws ResolutionPlugInException {
253
254                 String scClassName = null;
255                 if (config != null) {
256                         scClassName = config.getAttribute("class");
257                 }
258                 if (scClassName == null || scClassName.equals("")) {
259                         log.debug("Using default Statement Creator.");
260                         scClassName = DefaultStatementCreator.class.getName();
261                 }
262                 try {
263                         Class scClass = Class.forName(scClassName);
264
265                         Class[] params = new Class[1];
266                         params[0] = Class.forName("org.w3c.dom.Element");
267                         try {
268                                 Constructor implementorConstructor = scClass.getConstructor(params);
269                                 Object[] args = new Object[1];
270                                 args[0] = config;
271                                 log.debug("Initializing Statement Creator of type (" + scClass.getName() + ").");
272                                 statementCreator = (JDBCStatementCreator) implementorConstructor.newInstance(args);
273                         } catch (NoSuchMethodException nsme) {
274                                 log.debug(
275                                         "Implementation constructor does have a parameterized constructor, attempting to load default.");
276                                 statementCreator = (JDBCStatementCreator) scClass.newInstance();
277                         }
278                         log.debug("Statement Creator implementation loaded.");
279
280                 } catch (ClassNotFoundException e) {
281                         log.error("The supplied Statement Creator class could not be found: " + e);
282                         throw new ResolutionPlugInException(
283                                 "The supplied Statement Creator class could not be found: " + e.getMessage());
284                 } catch (Exception e) {
285                         log.error("Unable to instantiate Statement Creator implementation: " + e);
286                         throw new ResolutionPlugInException(
287                                 "Unable to instantiate Statement Creator implementation: " + e.getMessage());
288                 }
289         }
290
291         public Attributes resolve(Principal principal, String requester, Dependencies depends)
292                 throws ResolutionPlugInException {
293
294                 log.debug("Resolving connector: (" + getId() + ")");
295
296                 //Retrieve a connection from the connection pool
297                 Connection conn = null;
298                 try {
299                         conn = dataSource.getConnection();
300                         log.debug("Connection retrieved from pool");
301                 } catch (Exception e) {
302                         log.error("Unable to fetch a connection from the pool");
303                         throw new ResolutionPlugInException("Unable to fetch a connection from the pool: " + e.getMessage());
304                 }
305                 if (conn == null) {
306                         log.error("Pool didn't return a propertly initialized connection.");
307                         throw new ResolutionPlugInException("Pool didn't return a properly initialized connection.");
308                 }
309
310                 //Setup and execute a (pooled) prepared statement
311                 ResultSet rs = null;
312                 PreparedStatement preparedStatement;
313                 try {
314                         preparedStatement = conn.prepareStatement(searchVal);
315                         statementCreator.create(preparedStatement, principal, requester, depends);
316                         rs = preparedStatement.executeQuery();
317                         if (!rs.next()) {
318                                 return new BasicAttributes();
319                         }
320                 } catch (JDBCStatementCreatorException e) {
321                         log.error("An ERROR occured while constructing the query");
322                         throw new ResolutionPlugInException("An ERROR occured while constructing the query: " + e.getMessage());
323                 } catch (SQLException e) {
324                         log.error("An ERROR occured while executing the query");
325                         throw new ResolutionPlugInException("An ERROR occured while executing the query: " + e.getMessage());
326                 }
327
328                 //Extract attributes from the ResultSet
329                 try {
330                         return extractor.extractAttributes(rs);
331
332                 } catch (JDBCAttributeExtractorException e) {
333                         log.error("An ERROR occured while extracting attributes from result set");
334                         throw new ResolutionPlugInException(
335                                 "An ERROR occured while extracting attributes from result set: " + e.getMessage());
336                 } finally {
337                         try {
338                                 if (preparedStatement != null) {
339                                         preparedStatement.close();
340                                 }
341                         } catch (SQLException e) {
342                                 log.error("An error occured while closing the prepared statement: " + e);
343                                 throw new ResolutionPlugInException("An error occured while closing the prepared statement: " + e);
344                         }
345                         try {
346                                 rs.close();
347                         } catch (SQLException e) {
348                                 log.error("An error occured while closing the result set: " + e);
349                                 throw new ResolutionPlugInException("An error occured while closing the result set: " + e);
350                         }
351
352                         try {
353                                 conn.close();
354                         } catch (SQLException e) {
355                                 log.error("An error occured while closing the database connection: " + e);
356                                 throw new ResolutionPlugInException("An error occured while closing the database connection: " + e);
357                         }
358                 }
359         }
360
361         /** 
362          * Loads the driver used to access the database
363          * @param driver The driver used to access the database
364          * @throws ResolutionPlugInException If there is a failure to load the driver
365          */
366         public void loadDriver(String driver) throws ResolutionPlugInException {
367                 try {
368                         Class.forName(driver).newInstance();
369                         log.debug("Loading JDBC driver: " + driver);
370                 } catch (Exception e) {
371                         log.error("An error loading database driver: " + e);
372                         throw new ResolutionPlugInException(
373                                 "An IllegalAccessException occured while loading database driver: " + e.getMessage());
374                 }
375                 log.debug("Driver loaded.");
376         }
377
378     /**
379      * @see edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn#getFailoverDependencyId()
380      */
381     public String getFailoverDependencyId() {
382         return failover;
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 void setParameterValue(PreparedStatement preparedStatement, int valueIndex, Dependencies depends)
693                         throws JDBCStatementCreatorException {
694
695                         //handle values from DataConnectors
696                         if (referencesConnector) {
697                                 Attributes attributes = depends.getConnectorResolution(connectorId);
698                                 if (attributes == null) {
699                                         log.error(
700                                                 "Statement Creator misconfiguration: Connector ("
701                                                         + connectorId
702                                                         + ") is not a dependency of this JDBCDataConnector.");
703                                         throw new JDBCStatementCreatorException(
704                                                 "Statement Creator misconfiguration: Connector ("
705                                                         + connectorId
706                                                         + ") is not a dependency of this JDBCDataConnector.");
707                                 }
708
709                                 Attribute attribute = attributes.get(attributeName);
710                                 if (attribute == null || attribute.size() < 1) {
711                                         if (nullMissing) {
712                                                 try {
713                                                         preparedStatement.setNull(valueIndex, Types.NULL);
714                                                         return;
715                                                 } catch (SQLException e) {
716                                                         log.error(
717                                                                 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
718                                                 }
719                                         }
720                                         log.error("Cannot parameterize prepared statement: missing dependency value.");
721                                         throw new JDBCStatementCreatorException("Cannot parameterize prepared statement: missing dependency value.");
722                                 }
723
724                                 if (attribute.size() > 1) {
725                                         log.error("Statement Creator encountered a multivalued dependent attribute.");
726                                         throw new JDBCStatementCreatorException("Statement Creator encountered a multivalued dependent attribute.");
727                                 }
728
729                                 try {
730                                         setSpecificParameter(preparedStatement, valueIndex, attribute.get());
731                                         return;
732                                 } catch (NamingException e) {
733                                         log.error(
734                                                 "Statement Creator encountered an error while extracting attributes from a Data Conector: "
735                                                         + e);
736                                         throw new JDBCStatementCreatorException(
737                                                 "Statement Creator encountered an error while extracting attributes from a Data Conector: "
738                                                         + e.getMessage());
739                                 }
740                         }
741
742                         //handle values from AttributeDefinitons
743                         ResolverAttribute attribute = depends.getAttributeResolution(attributeName);
744                         if (attribute != null) {
745                                 Iterator iterator = attribute.getValues();
746                                 if (iterator.hasNext()) {
747                                         setSpecificParameter(preparedStatement, valueIndex, iterator.next());
748                                         if (iterator.hasNext()) {
749                                                 log.error("Statement Creator encountered a multivalued dependent attribute.");
750                                                 throw new JDBCStatementCreatorException("Statement Creator encountered a multivalued dependent attribute.");
751                                         }
752                                         return;
753                                 }
754                         }
755                         if (nullMissing) {
756                                 try {
757                                         preparedStatement.setNull(valueIndex, Types.NULL);
758                                         return;
759                                 } catch (SQLException e) {
760                                         log.error(
761                                                 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
762                                 }
763                         }
764                         log.error("Cannot parameterize prepared statement: missing dependency value.");
765                         throw new JDBCStatementCreatorException("Cannot parameterize prepared statement: missing dependency value.");
766                 }
767
768                 protected void setNullMissing(boolean nullMissing) {
769                         this.nullMissing = nullMissing;
770                 }
771
772                 private void setSpecificParameter(PreparedStatement preparedStatement, int valueIndex, Object object)
773                         throws JDBCStatementCreatorException {
774
775                         if (object == null) {
776                                 try {
777                                         preparedStatement.setNull(valueIndex, Types.NULL);
778                                         return;
779                                 } catch (SQLException e) {
780                                         log.error(
781                                                 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
782                                         throw new JDBCStatementCreatorException("Encountered a problem while attempting to convert missing attribute value to null parameter.");
783                                 }
784                         } else if (type.equalsIgnoreCase("String")) {
785                                 setString(preparedStatement, valueIndex, object);
786                         } else if (type.equalsIgnoreCase("Integer")) {
787                                 setInteger(preparedStatement, valueIndex, object);
788                         } else if (type.equalsIgnoreCase("Byte")) {
789                                 setByte(preparedStatement, valueIndex, object);
790                         } else if (type.equalsIgnoreCase("Double")) {
791                                 setDouble(preparedStatement, valueIndex, object);
792                         } else if (type.equalsIgnoreCase("Float")) {
793                                 setFloat(preparedStatement, valueIndex, object);
794                         } else if (type.equalsIgnoreCase("Long")) {
795                                 setLong(preparedStatement, valueIndex, object);
796                         } else if (type.equalsIgnoreCase("Short")) {
797                                 setShort(preparedStatement, valueIndex, object);
798                         } else if (type.equalsIgnoreCase("Boolean")) {
799                                 setBoolean(preparedStatement, valueIndex, object);
800                         } else if (type.equalsIgnoreCase("Date")) {
801                                 setDate(preparedStatement, valueIndex, object);
802                         } else if (type.equalsIgnoreCase("Blob")) {
803                                 setBlob(preparedStatement, valueIndex, object);
804                         } else if (type.equalsIgnoreCase("Clob")) {
805                                 setClob(preparedStatement, valueIndex, object);
806                         } else {
807                                 setString(preparedStatement, valueIndex, object);
808                         }
809                 }
810
811                 private void setClob(PreparedStatement preparedStatement, int valueIndex, Object object)
812                         throws JDBCStatementCreatorException {
813                         if (object instanceof Clob) {
814                                 try {
815                                         preparedStatement.setClob(valueIndex, (Clob) object);
816                                         return;
817                                 } catch (SQLException e) {
818                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
819                                         throw new JDBCStatementCreatorException(
820                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
821                                 }
822                         }
823                         log.error("Encountered a dependency with an invalid java type.");
824                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
825                 }
826
827                 private void setBlob(PreparedStatement preparedStatement, int valueIndex, Object object)
828                         throws JDBCStatementCreatorException {
829                         if (object instanceof Blob) {
830                                 try {
831                                         preparedStatement.setBlob(valueIndex, (Blob) object);
832                                         return;
833                                 } catch (SQLException e) {
834                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
835                                         throw new JDBCStatementCreatorException(
836                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
837                                 }
838                         }
839                         log.error("Encountered a dependency with an invalid java type.");
840                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
841                 }
842
843                 private void setDate(PreparedStatement preparedStatement, int valueIndex, Object object)
844                         throws JDBCStatementCreatorException {
845
846                         if (object instanceof java.sql.Date) {
847                                 try {
848                                         preparedStatement.setDate(valueIndex, (java.sql.Date) object);
849                                         return;
850                                 } catch (SQLException e) {
851                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
852                                         throw new JDBCStatementCreatorException(
853                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
854                                 }
855                         } else if (object instanceof java.util.Date) {
856                                 try {
857                                         //If you want to be frustrated by the java class library, look no further...
858                                         preparedStatement.setDate(valueIndex, new java.sql.Date(((java.util.Date) object).getTime()));
859                                         return;
860                                 } catch (SQLException e) {
861                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
862                                         throw new JDBCStatementCreatorException(
863                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
864                                 }
865                         } else if (object instanceof Long) {
866                                 try {
867                                         preparedStatement.setDate(valueIndex, new java.sql.Date(((Long) object).longValue()));
868                                         return;
869                                 } catch (SQLException e) {
870                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
871                                         throw new JDBCStatementCreatorException(
872                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
873                                 }
874                         } else if (object instanceof String) {
875                                 try {
876                                         preparedStatement.setDate(
877                                                 valueIndex,
878                                                 new java.sql.Date(new SimpleDateFormat().parse((String) object).getTime()));
879                                         return;
880                                 } catch (Exception e) {
881                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
882                                         throw new JDBCStatementCreatorException(
883                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
884                                 }
885                         }
886                         log.error("Encountered a dependency with an invalid java type.");
887                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
888                 }
889
890                 private void setBoolean(PreparedStatement preparedStatement, int valueIndex, Object object)
891                         throws JDBCStatementCreatorException {
892                         if (object instanceof Boolean) {
893                                 try {
894                                         preparedStatement.setBoolean(valueIndex, ((Boolean) object).booleanValue());
895                                         return;
896                                 } catch (SQLException e) {
897                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
898                                         throw new JDBCStatementCreatorException(
899                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
900                                 }
901                         } else if (object instanceof String) {
902                                 try {
903                                         preparedStatement.setBoolean(valueIndex, new Boolean((String) object).booleanValue());
904                                         return;
905                                 } catch (Exception e) {
906                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
907                                         throw new JDBCStatementCreatorException(
908                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
909                                 }
910                         }
911                         log.error("Encountered a dependency with an invalid java type.");
912                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
913                 }
914
915                 private void setShort(PreparedStatement preparedStatement, int valueIndex, Object object)
916                         throws JDBCStatementCreatorException {
917                         if (object instanceof Boolean) {
918                                 try {
919                                         preparedStatement.setShort(valueIndex, ((Short) object).shortValue());
920                                         return;
921                                 } catch (SQLException e) {
922                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
923                                         throw new JDBCStatementCreatorException(
924                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
925                                 }
926                         } else if (object instanceof String) {
927                                 try {
928                                         preparedStatement.setShort(valueIndex, new Short((String) object).shortValue());
929                                         return;
930                                 } catch (Exception e) {
931                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
932                                         throw new JDBCStatementCreatorException(
933                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
934                                 }
935                         }
936                         log.error("Encountered a dependency with an invalid java type.");
937                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
938                 }
939
940                 private void setLong(PreparedStatement preparedStatement, int valueIndex, Object object)
941                         throws JDBCStatementCreatorException {
942                         if (object instanceof Long || object instanceof Integer || object instanceof Short) {
943                                 try {
944                                         preparedStatement.setLong(valueIndex, ((Number) object).longValue());
945                                         return;
946                                 } catch (SQLException e) {
947                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
948                                         throw new JDBCStatementCreatorException(
949                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
950                                 }
951                         } else if (object instanceof String) {
952                                 try {
953                                         preparedStatement.setLong(valueIndex, new Long((String) object).longValue());
954                                         return;
955                                 } catch (Exception e) {
956                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
957                                         throw new JDBCStatementCreatorException(
958                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
959                                 }
960                         }
961                         log.error("Encountered a dependency with an invalid java type.");
962                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
963                 }
964
965                 private void setFloat(PreparedStatement preparedStatement, int valueIndex, Object object)
966                         throws JDBCStatementCreatorException {
967                         if (object instanceof Float) {
968                                 try {
969                                         preparedStatement.setFloat(valueIndex, ((Float) object).floatValue());
970                                         return;
971                                 } catch (SQLException e) {
972                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
973                                         throw new JDBCStatementCreatorException(
974                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
975                                 }
976                         } else if (object instanceof String) {
977                                 try {
978                                         preparedStatement.setFloat(valueIndex, new Float((String) object).floatValue());
979                                         return;
980                                 } catch (Exception e) {
981                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
982                                         throw new JDBCStatementCreatorException(
983                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
984                                 }
985                         }
986                         log.error("Encountered a dependency with an invalid java type.");
987                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
988                 }
989
990                 private void setDouble(PreparedStatement preparedStatement, int valueIndex, Object object)
991                         throws JDBCStatementCreatorException {
992                         if (object instanceof Double || object instanceof Float) {
993                                 try {
994                                         preparedStatement.setDouble(valueIndex, ((Number) object).doubleValue());
995                                         return;
996                                 } catch (SQLException e) {
997                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
998                                         throw new JDBCStatementCreatorException(
999                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1000                                 }
1001                         } else if (object instanceof String) {
1002                                 try {
1003                                         preparedStatement.setDouble(valueIndex, new Double((String) object).doubleValue());
1004                                         return;
1005                                 } catch (Exception e) {
1006                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1007                                         throw new JDBCStatementCreatorException(
1008                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1009                                 }
1010                         }
1011                         log.error("Encountered a dependency with an invalid java type.");
1012                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1013                 }
1014
1015                 private void setByte(PreparedStatement preparedStatement, int valueIndex, Object object)
1016                         throws JDBCStatementCreatorException {
1017                         if (object instanceof Byte) {
1018                                 try {
1019                                         preparedStatement.setByte(valueIndex, ((Byte) object).byteValue());
1020                                         return;
1021                                 } catch (SQLException e) {
1022                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1023                                         throw new JDBCStatementCreatorException(
1024                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1025                                 }
1026                         } else if (object instanceof String) {
1027                                 try {
1028                                         preparedStatement.setByte(valueIndex, new Byte((String) object).byteValue());
1029                                         return;
1030                                 } catch (Exception e) {
1031                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1032                                         throw new JDBCStatementCreatorException(
1033                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1034                                 }
1035                         }
1036                         log.error("Encountered a dependency with an invalid java type.");
1037                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1038                 }
1039
1040                 private void setInteger(PreparedStatement preparedStatement, int valueIndex, Object object)
1041                         throws JDBCStatementCreatorException {
1042                         if (object instanceof Integer || object instanceof Short) {
1043                                 try {
1044                                         preparedStatement.setInt(valueIndex, ((Number) object).intValue());
1045                                         return;
1046                                 } catch (SQLException e) {
1047                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1048                                         throw new JDBCStatementCreatorException(
1049                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1050                                 }
1051                         } else if (object instanceof String) {
1052                                 try {
1053                                         preparedStatement.setInt(valueIndex, new Integer((String) object).intValue());
1054                                         return;
1055                                 } catch (Exception e) {
1056                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1057                                         throw new JDBCStatementCreatorException(
1058                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1059                                 }
1060                         }
1061                         log.error("Encountered a dependency with an invalid java type.");
1062                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1063                 }
1064
1065                 private void setString(PreparedStatement preparedStatement, int valueIndex, Object object)
1066                         throws JDBCStatementCreatorException {
1067                         if (object instanceof String) {
1068                                 try {
1069                                         preparedStatement.setString(valueIndex, (String) object);
1070                                         return;
1071                                 } catch (SQLException e) {
1072                                         log.error("Encountered an error while adding parameter to prepared statement: " + e);
1073                                         throw new JDBCStatementCreatorException(
1074                                                 "Encountered an error while adding parameter to prepared statement: " + e.getMessage());
1075                                 }
1076                         }
1077                         log.error("Encountered a dependency with an invalid java type.");
1078                         throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1079                 }
1080         }
1081 }