1 56 57 package org.objectstyle.cayenne.conf; 58 59 import javax.naming.Context ; 60 import javax.naming.InitialContext ; 61 import javax.naming.NamingException ; 62 import javax.sql.DataSource ; 63 64 import org.apache.log4j.Level; 65 import org.apache.log4j.Logger; 66 import org.objectstyle.cayenne.access.QueryLogger; 67 import org.objectstyle.cayenne.util.Util; 68 69 74 public class JNDIDataSourceFactory implements DataSourceFactory { 75 76 private static final Logger logObj = Logger.getLogger(JNDIDataSourceFactory.class); 77 78 protected Configuration parentConfig; 79 80 84 public DataSource getDataSource(String location) throws Exception { 85 return getDataSource(location, Level.DEBUG); 86 } 87 88 public void initializeWithParentConfiguration(Configuration conf) { 89 this.parentConfig = conf; 90 } 91 92 96 public DataSource getDataSource(String location, Level logLevel) throws Exception { 97 if (logLevel == null) { 98 logLevel = Level.DEBUG; 99 } 100 101 try { 102 return loadViaJNDI(location, logLevel); 103 } 104 catch (Exception ex) { 105 106 logObj 107 .debug("failed JNDI lookup, attempt to load from local preferences. Location key:" 108 + location); 109 110 try { 112 return loadFromPreferences(location, logLevel); 113 } 114 catch (Exception preferencesException) { 115 116 logObj.debug("failed loading from local preferences", Util 117 .unwindException(preferencesException)); 118 119 QueryLogger.logConnectFailure(logLevel, ex); 121 throw ex; 122 } 123 } 124 } 125 126 DataSource loadViaJNDI(String location, Level logLevel) throws NamingException { 127 QueryLogger.logConnect(logLevel, location); 128 129 Context initCtx = new InitialContext (); 130 DataSource ds; 131 try { 132 Context envCtx = (Context ) initCtx.lookup("java:comp/env"); 133 ds = (DataSource ) envCtx.lookup(location); 134 } 135 catch (NamingException namingEx) { 136 ds = (DataSource ) initCtx.lookup(location); 138 } 139 140 QueryLogger.logConnectSuccess(logLevel); 141 return ds; 142 } 143 144 DataSource loadFromPreferences(String location, Level logLevel) throws Exception { 145 148 DataSourceFactory prefsFactory = (DataSourceFactory) Class 149 .forName( 150 "org.objectstyle.cayenne.modeler.pref.PreferencesDataSourceFactory") 151 .newInstance(); 152 153 prefsFactory.initializeWithParentConfiguration(parentConfig); 154 return prefsFactory.getDataSource(location, logLevel); 155 } 156 } 157 | Popular Tags |