2 * Copyright (c) 2003 National Research Council of Canada
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:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
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.
26 package edu.internet2.middleware.shibboleth.aa.attrresolv.provider;
28 import java.io.PrintWriter;
29 import java.lang.reflect.Constructor;
30 import java.security.Principal;
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;
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;
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;
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;
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>.
80 * Data Connector that uses JDBC to access user attributes stored in databases.
82 * @author David Dearman (dearman@cs.dal.ca)
83 * @author Walter Hoehn (wassa@columbia.edu)
84 * @author Scott Cantor
87 public class JDBCDataConnector extends BaseResolutionPlugIn implements DataConnectorPlugIn {
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;
96 public JDBCDataConnector(Element e) throws ResolutionPlugInException {
100 NodeList failoverNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "FailoverDependency");
101 if (failoverNodes.getLength() > 0) {
102 failover = ((Element)failoverNodes.item(0)).getAttribute("requires");
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();
110 if (searchVal == null || searchVal.equals("")) {
111 log.error("Database query must be specified.");
112 throw new ResolutionPlugInException("Database query must be specified.");
115 //Load the supplied JDBC driver
116 String dbDriverName = e.getAttribute("dbDriver");
117 if (dbDriverName != null && (!dbDriverName.equals(""))) {
118 loadDriver(dbDriverName);
121 //Load site-specific implementation classes
122 setupAttributeExtractor(
123 (Element) e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "AttributeExtractor").item(
125 setupStatementCreator(
126 (Element) e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "StatementCreator").item(0));
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");
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 + ")");
144 log.error("Property is malformed.");
145 throw new ResolutionPlugInException("Property is malformed.");
149 //Initialize a pooling Data Source
153 if (e.getAttributeNode("maxActive") != null) {
154 maxActive = Integer.parseInt(e.getAttribute("maxActive"));
156 if (e.getAttributeNode("maxIdle") != null) {
157 maxIdle = Integer.parseInt(e.getAttribute("maxIdle"));
159 } catch (NumberFormatException ex) {
160 log.error("Malformed pooling limits: using defaults.");
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");
166 setupDataSource(e.getAttribute("dbURL"), props, maxActive, maxIdle);
170 * Initialize a Pooling Data Source
172 private void setupDataSource(String dbURL, Properties props, int maxActive, int maxIdle) throws ResolutionPlugInException {
174 GenericObjectPool objectPool = new GenericObjectPool(null);
177 objectPool.setMaxActive(maxActive);
180 objectPool.setMaxIdle(maxIdle);
183 objectPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
185 ConnectionFactory connFactory = null;
186 PoolableConnectionFactory poolConnFactory = null;
189 connFactory = new DriverManagerConnectionFactory(dbURL, props);
190 log.debug("Connection factory initialized.");
191 } catch (Exception ex) {
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());
199 new PoolableConnectionFactory(
202 new StackKeyedObjectPoolFactory(),
206 } catch (Exception ex) {
207 log.debug("Poolable connection factory error");
210 dataSource = new PoolingDataSource(objectPool);
211 log.info("Data Source initialized.");
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.");
221 * Instantiate an Attribute Extractor, using the default if none was configured
223 private void setupAttributeExtractor(Element config) throws ResolutionPlugInException {
225 String className = null;
226 if (config != null) {
227 className = config.getAttribute("class");
229 if (className == null || className.equals("")) {
230 log.debug("Using default Attribute Extractor.");
231 className = DefaultAE.class.getName();
234 Class aeClass = Class.forName(className);
235 extractor = (JDBCAttributeExtractor) aeClass.newInstance();
236 log.debug("Attribute Extractor implementation loaded.");
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());
250 * Instantiate a Statement Creator, using the default if none was configured
252 private void setupStatementCreator(Element config) throws ResolutionPlugInException {
254 String scClassName = null;
255 if (config != null) {
256 scClassName = config.getAttribute("class");
258 if (scClassName == null || scClassName.equals("")) {
259 log.debug("Using default Statement Creator.");
260 scClassName = DefaultStatementCreator.class.getName();
263 Class scClass = Class.forName(scClassName);
265 Class[] params = new Class[1];
266 params[0] = Class.forName("org.w3c.dom.Element");
268 Constructor implementorConstructor = scClass.getConstructor(params);
269 Object[] args = new Object[1];
271 log.debug("Initializing Statement Creator of type (" + scClass.getName() + ").");
272 statementCreator = (JDBCStatementCreator) implementorConstructor.newInstance(args);
273 } catch (NoSuchMethodException nsme) {
275 "Implementation constructor does have a parameterized constructor, attempting to load default.");
276 statementCreator = (JDBCStatementCreator) scClass.newInstance();
278 log.debug("Statement Creator implementation loaded.");
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());
291 public Attributes resolve(Principal principal, String requester, Dependencies depends)
292 throws ResolutionPlugInException {
294 log.debug("Resolving connector: (" + getId() + ")");
296 //Retrieve a connection from the connection pool
297 Connection conn = null;
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());
306 log.error("Pool didn't return a propertly initialized connection.");
307 throw new ResolutionPlugInException("Pool didn't return a properly initialized connection.");
310 //Setup and execute a (pooled) prepared statement
312 PreparedStatement preparedStatement;
314 preparedStatement = conn.prepareStatement(searchVal);
315 statementCreator.create(preparedStatement, principal, requester, depends);
316 rs = preparedStatement.executeQuery();
318 return new BasicAttributes();
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());
328 //Extract attributes from the ResultSet
330 return extractor.extractAttributes(rs);
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());
338 if (preparedStatement != null) {
339 preparedStatement.close();
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);
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);
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);
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
366 public void loadDriver(String driver) throws ResolutionPlugInException {
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());
375 log.debug("Driver loaded.");
379 * @see edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn#getFailoverDependencyId()
381 public String getFailoverDependencyId() {
385 private class Log4jPrintWriter extends PrintWriter {
387 private Priority level;
388 private Logger logger;
389 private StringBuffer text = new StringBuffer("");
391 private Log4jPrintWriter(Logger logger, org.apache.log4j.Priority level) {
394 this.logger = logger;
397 public void close() {
401 public void flush() {
402 if (!text.toString().equals("")) {
403 logger.log(level, text.toString());
408 public void print(boolean b) {
412 public void print(char c) {
416 public void print(char[] s) {
420 public void print(double d) {
424 public void print(float f) {
428 public void print(int i) {
432 public void print(long l) {
436 public void print(Object obj) {
440 public void print(String s) {
444 public void println() {
445 if (!text.toString().equals("")) {
446 logger.log(level, text.toString());
451 public void println(boolean x) {
453 logger.log(level, text.toString());
457 public void println(char x) {
459 logger.log(level, text.toString());
463 public void println(char[] x) {
465 logger.log(level, text.toString());
469 public void println(double x) {
471 logger.log(level, text.toString());
475 public void println(float x) {
477 logger.log(level, text.toString());
481 public void println(int x) {
483 logger.log(level, text.toString());
487 public void println(long x) {
489 logger.log(level, text.toString());
493 public void println(Object x) {
495 logger.log(level, text.toString());
499 public void println(String x) {
501 logger.log(level, text.toString());
508 * The default attribute extractor.
510 class DefaultAE implements JDBCAttributeExtractor {
512 private static Logger log = Logger.getLogger(DefaultAE.class.getName());
515 * Method of extracting the attributes from the supplied result set.
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
521 public BasicAttributes extractAttributes(ResultSet rs) throws JDBCAttributeExtractorException {
522 BasicAttributes attributes = new BasicAttributes();
526 // Get metadata about result set.
527 ResultSetMetaData rsmd = rs.getMetaData();
528 int numColumns = rsmd.getColumnCount();
529 log.debug("Number of returned columns: " + numColumns);
532 for (int i = 1; i <= numColumns; i++) {
533 String columnName = rsmd.getColumnName(i);
534 Object columnValue = rs.getObject(columnName);
535 if (log.isDebugEnabled()) {
539 + ". ColumnType = " + rsmd.getColumnTypeName(i)
543 + (columnValue != null ? columnValue.toString() : "(null)"));
546 BasicAttribute ba = new BasicAttribute(columnName, true);
547 ba.add(row,columnValue);
551 attributes.get(columnName).add(row,columnValue);
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());
566 class DefaultStatementCreator implements JDBCStatementCreator {
568 private static Logger log = Logger.getLogger(DefaultStatementCreator.class.getName());
571 PreparedStatement preparedStatement,
574 Dependencies depends)
575 throws JDBCStatementCreatorException {
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...
584 preparedStatement.setString(i++, principal.getName());
586 } catch (SQLException e) {
587 //Ignore any additional exceptions, assume parameters simply don't exist.
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());
597 class DependencyStatementCreator implements JDBCStatementCreator {
599 private static Logger log = Logger.getLogger(DependencyStatementCreator.class.getName());
600 private ArrayList parameters = new ArrayList();
602 public DependencyStatementCreator(Element conf) throws JDBCStatementCreatorException {
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");
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.");
618 if (parameter.getAttribute("connectorId") != null && (!parameter.getAttribute("connectorId").equals(""))) {
622 parameter.getAttribute("attributeName"),
623 parameter.getAttribute("connectorId")));
625 parameters.add(new Parameter(type, parameter.getAttribute("attributeName")));
629 if (parameter.getAttribute("nullMissing") != null && (!parameter.getAttribute("nullMissing").equals(""))) {
630 if (parameter.getAttribute("nullMissing").equalsIgnoreCase("FALSE")) {
631 ((Parameter) parameters.get(i)).setNullMissing(false);
635 log.debug("Parameters configured: " + parameters.size());
639 PreparedStatement preparedStatement,
642 Dependencies depends)
643 throws JDBCStatementCreatorException {
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);
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());
658 protected class Parameter {
660 private String attributeName;
661 private boolean referencesConnector = false;
662 private String connectorId;
663 private boolean nullMissing = true;
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.");
681 this.attributeName = attributeName;
684 protected Parameter(String type, String attributeName, String connectorId)
685 throws JDBCStatementCreatorException {
686 this(type, attributeName);
687 referencesConnector = true;
688 this.connectorId = connectorId;
692 protected void setParameterValue(PreparedStatement preparedStatement, int valueIndex, Dependencies depends)
693 throws JDBCStatementCreatorException {
695 //handle values from DataConnectors
696 if (referencesConnector) {
697 Attributes attributes = depends.getConnectorResolution(connectorId);
698 if (attributes == null) {
700 "Statement Creator misconfiguration: Connector ("
702 + ") is not a dependency of this JDBCDataConnector.");
703 throw new JDBCStatementCreatorException(
704 "Statement Creator misconfiguration: Connector ("
706 + ") is not a dependency of this JDBCDataConnector.");
709 Attribute attribute = attributes.get(attributeName);
710 if (attribute == null || attribute.size() < 1) {
713 preparedStatement.setNull(valueIndex, Types.NULL);
715 } catch (SQLException e) {
717 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
720 log.error("Cannot parameterize prepared statement: missing dependency value.");
721 throw new JDBCStatementCreatorException("Cannot parameterize prepared statement: missing dependency value.");
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.");
730 setSpecificParameter(preparedStatement, valueIndex, attribute.get());
732 } catch (NamingException e) {
734 "Statement Creator encountered an error while extracting attributes from a Data Conector: "
736 throw new JDBCStatementCreatorException(
737 "Statement Creator encountered an error while extracting attributes from a Data Conector: "
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.");
757 preparedStatement.setNull(valueIndex, Types.NULL);
759 } catch (SQLException e) {
761 "Encountered a problem while attempting to convert missing attribute value to null parameter.");
764 log.error("Cannot parameterize prepared statement: missing dependency value.");
765 throw new JDBCStatementCreatorException("Cannot parameterize prepared statement: missing dependency value.");
768 protected void setNullMissing(boolean nullMissing) {
769 this.nullMissing = nullMissing;
772 private void setSpecificParameter(PreparedStatement preparedStatement, int valueIndex, Object object)
773 throws JDBCStatementCreatorException {
775 if (object == null) {
777 preparedStatement.setNull(valueIndex, Types.NULL);
779 } catch (SQLException e) {
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.");
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);
807 setString(preparedStatement, valueIndex, object);
811 private void setClob(PreparedStatement preparedStatement, int valueIndex, Object object)
812 throws JDBCStatementCreatorException {
813 if (object instanceof Clob) {
815 preparedStatement.setClob(valueIndex, (Clob) object);
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());
823 log.error("Encountered a dependency with an invalid java type.");
824 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
827 private void setBlob(PreparedStatement preparedStatement, int valueIndex, Object object)
828 throws JDBCStatementCreatorException {
829 if (object instanceof Blob) {
831 preparedStatement.setBlob(valueIndex, (Blob) object);
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());
839 log.error("Encountered a dependency with an invalid java type.");
840 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
843 private void setDate(PreparedStatement preparedStatement, int valueIndex, Object object)
844 throws JDBCStatementCreatorException {
846 if (object instanceof java.sql.Date) {
848 preparedStatement.setDate(valueIndex, (java.sql.Date) object);
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());
855 } else if (object instanceof java.util.Date) {
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()));
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());
865 } else if (object instanceof Long) {
867 preparedStatement.setDate(valueIndex, new java.sql.Date(((Long) object).longValue()));
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());
874 } else if (object instanceof String) {
876 preparedStatement.setDate(
878 new java.sql.Date(new SimpleDateFormat().parse((String) object).getTime()));
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());
886 log.error("Encountered a dependency with an invalid java type.");
887 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
890 private void setBoolean(PreparedStatement preparedStatement, int valueIndex, Object object)
891 throws JDBCStatementCreatorException {
892 if (object instanceof Boolean) {
894 preparedStatement.setBoolean(valueIndex, ((Boolean) object).booleanValue());
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());
901 } else if (object instanceof String) {
903 preparedStatement.setBoolean(valueIndex, new Boolean((String) object).booleanValue());
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());
911 log.error("Encountered a dependency with an invalid java type.");
912 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
915 private void setShort(PreparedStatement preparedStatement, int valueIndex, Object object)
916 throws JDBCStatementCreatorException {
917 if (object instanceof Boolean) {
919 preparedStatement.setShort(valueIndex, ((Short) object).shortValue());
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());
926 } else if (object instanceof String) {
928 preparedStatement.setShort(valueIndex, new Short((String) object).shortValue());
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());
936 log.error("Encountered a dependency with an invalid java type.");
937 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
940 private void setLong(PreparedStatement preparedStatement, int valueIndex, Object object)
941 throws JDBCStatementCreatorException {
942 if (object instanceof Long || object instanceof Integer || object instanceof Short) {
944 preparedStatement.setLong(valueIndex, ((Number) object).longValue());
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());
951 } else if (object instanceof String) {
953 preparedStatement.setLong(valueIndex, new Long((String) object).longValue());
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());
961 log.error("Encountered a dependency with an invalid java type.");
962 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
965 private void setFloat(PreparedStatement preparedStatement, int valueIndex, Object object)
966 throws JDBCStatementCreatorException {
967 if (object instanceof Float) {
969 preparedStatement.setFloat(valueIndex, ((Float) object).floatValue());
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());
976 } else if (object instanceof String) {
978 preparedStatement.setFloat(valueIndex, new Float((String) object).floatValue());
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());
986 log.error("Encountered a dependency with an invalid java type.");
987 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
990 private void setDouble(PreparedStatement preparedStatement, int valueIndex, Object object)
991 throws JDBCStatementCreatorException {
992 if (object instanceof Double || object instanceof Float) {
994 preparedStatement.setDouble(valueIndex, ((Number) object).doubleValue());
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());
1001 } else if (object instanceof String) {
1003 preparedStatement.setDouble(valueIndex, new Double((String) object).doubleValue());
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());
1011 log.error("Encountered a dependency with an invalid java type.");
1012 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1015 private void setByte(PreparedStatement preparedStatement, int valueIndex, Object object)
1016 throws JDBCStatementCreatorException {
1017 if (object instanceof Byte) {
1019 preparedStatement.setByte(valueIndex, ((Byte) object).byteValue());
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());
1026 } else if (object instanceof String) {
1028 preparedStatement.setByte(valueIndex, new Byte((String) object).byteValue());
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());
1036 log.error("Encountered a dependency with an invalid java type.");
1037 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1040 private void setInteger(PreparedStatement preparedStatement, int valueIndex, Object object)
1041 throws JDBCStatementCreatorException {
1042 if (object instanceof Integer || object instanceof Short) {
1044 preparedStatement.setInt(valueIndex, ((Number) object).intValue());
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());
1051 } else if (object instanceof String) {
1053 preparedStatement.setInt(valueIndex, new Integer((String) object).intValue());
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());
1061 log.error("Encountered a dependency with an invalid java type.");
1062 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");
1065 private void setString(PreparedStatement preparedStatement, int valueIndex, Object object)
1066 throws JDBCStatementCreatorException {
1067 if (object instanceof String) {
1069 preparedStatement.setString(valueIndex, (String) object);
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());
1077 log.error("Encountered a dependency with an invalid java type.");
1078 throw new JDBCStatementCreatorException("Encountered a dependency with an invalid java type.");