001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.servicemix.jdbc;
018
019 import java.sql.Connection;
020 import java.sql.SQLException;
021
022 import org.apache.commons.logging.Log;
023 import org.apache.commons.logging.LogFactory;
024 import org.apache.servicemix.finder.FactoryFinder;
025 import org.apache.servicemix.jdbc.adapter.DefaultJDBCAdapter;
026
027 public final class JDBCAdapterFactory {
028
029 private static final Log LOG = LogFactory.getLog(JDBCAdapterFactory.class);
030 private static FactoryFinder factoryFinder = new FactoryFinder("META-INF/services/org/apache/servicemix/jdbc/");
031
032 private JDBCAdapterFactory() {
033 }
034
035 public static JDBCAdapter getAdapter(Connection connection) {
036 JDBCAdapter adapter = null;
037 try {
038
039 // Make the filename file system safe.
040 String driverName = connection.getMetaData().getDriverName();
041 driverName = driverName.replaceAll("[^a-zA-Z0-9\\-]", "_").toLowerCase();
042
043 try {
044 adapter = (JDBCAdapter) factoryFinder.newInstance(driverName);
045 LOG.info("Database driver recognized: [" + driverName + "]");
046 } catch (Throwable e) {
047 LOG.warn("Database driver NOT recognized: [" + driverName
048 + "]. Will use default JDBC implementation.");
049 }
050
051 } catch (SQLException e) {
052 LOG.warn("JDBC error occurred while trying to detect database type. Will use default JDBC implementation: "
053 + e.getMessage());
054 log("Failure details: ", e);
055 }
056
057 // Use the default JDBC adapter if the
058 // Database type is not recognized.
059 if (adapter == null) {
060 adapter = new DefaultJDBCAdapter();
061 }
062
063 return adapter;
064 }
065
066 public static void log(String msg, SQLException e) {
067 if (LOG.isDebugEnabled()) {
068 String s = msg + e.getMessage();
069 while (e.getNextException() != null) {
070 e = e.getNextException();
071 s += ", due to: " + e.getMessage();
072 }
073 LOG.debug(s, e);
074 }
075 }
076 }