1 19 20 package org.apache.cayenne.conf; 21 22 import javax.naming.Context ; 23 import javax.naming.InitialContext ; 24 import javax.naming.NamingException ; 25 import javax.sql.DataSource ; 26 27 import org.apache.cayenne.access.QueryLogger; 28 import org.apache.cayenne.util.Util; 29 import org.apache.commons.logging.Log; 30 import org.apache.commons.logging.LogFactory; 31 32 37 public class JNDIDataSourceFactory implements DataSourceFactory { 38 39 private static final Log logger = LogFactory.getLog(JNDIDataSourceFactory.class); 40 41 protected Configuration parentConfig; 42 43 public void initializeWithParentConfiguration(Configuration conf) { 44 this.parentConfig = conf; 45 } 46 47 51 public DataSource getDataSource(String location) throws Exception { 52 53 try { 54 return loadViaJNDI(location); 55 } 56 catch (Exception ex) { 57 58 logger.info("failed JNDI lookup, attempt to load " 59 + "from local preferences. Location key:" 60 + location); 61 62 try { 64 return loadFromPreferences(location); 65 } 66 catch (Exception preferencesException) { 67 68 logger.info("failed loading from local preferences", Util 69 .unwindException(preferencesException)); 70 71 QueryLogger.logConnectFailure(ex); 73 throw ex; 74 } 75 } 76 } 77 78 DataSource loadViaJNDI(String location) throws NamingException { 79 QueryLogger.logConnect(location); 80 81 Context initCtx = new InitialContext (); 82 DataSource ds; 83 try { 84 Context envCtx = (Context ) initCtx.lookup("java:comp/env"); 85 ds = (DataSource ) envCtx.lookup(location); 86 } 87 catch (NamingException namingEx) { 88 ds = (DataSource ) initCtx.lookup(location); 90 } 91 92 QueryLogger.logConnectSuccess(); 93 return ds; 94 } 95 96 DataSource loadFromPreferences(String location) throws Exception { 97 100 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 101 DataSourceFactory prefsFactory = (DataSourceFactory) Class 102 .forName("org.apache.cayenne.modeler.pref.PreferencesDataSourceFactory", true, loader) 103 .newInstance(); 104 105 prefsFactory.initializeWithParentConfiguration(parentConfig); 106 return prefsFactory.getDataSource(location); 107 } 108 } 109 | Popular Tags |