001package net.sf.hajdbc.sql; 002 003import java.util.Hashtable; 004 005import javax.naming.Context; 006import javax.naming.Name; 007import javax.naming.RefAddr; 008import javax.naming.Reference; 009 010import net.sf.hajdbc.Database; 011import net.sf.hajdbc.DatabaseClusterConfigurationFactory; 012import net.sf.hajdbc.util.Objects; 013 014public class CommonDataSourceFactory<Z extends javax.sql.CommonDataSource, D extends Database<Z>, F extends CommonDataSourceProxyFactory<Z, D>> implements javax.naming.spi.ObjectFactory 015{ 016 public static final String CLUSTER = "cluster"; 017 public static final String CONFIG = "config"; 018 public static final String USER = "user"; 019 public static final String PASSWORD = "password"; 020 021 @Override 022 public Object getObjectInstance(Object object, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception 023 { 024 if ((object == null) || !(object instanceof Reference)) return null; 025 026 Reference reference = (Reference) object; 027 028 String className = reference.getClassName(); 029 030 if (className == null) return null; 031 032 Class<?> targetClass = this.getClass().getClassLoader().loadClass(className); 033 034 if (!targetClass.isAssignableFrom(CommonDataSource.class)) return null; 035 036 CommonDataSource<Z, D, F> result = targetClass.asSubclass(CommonDataSource.class).newInstance(); 037 038 RefAddr clusterAddr = reference.get(CLUSTER); 039 040 if (clusterAddr == null) return null; 041 042 Object clusterAddrContent = clusterAddr.getContent(); 043 044 if (!(clusterAddrContent instanceof String)) return null; 045 046 result.setCluster((String) clusterAddrContent); 047 048 RefAddr configAddr = reference.get(CONFIG); 049 050 if (configAddr == null) return null; 051 052 Object configAddrContent = configAddr.getContent(); 053 054 if (configAddrContent == null) return null; 055 056 if (configAddrContent instanceof String) 057 { 058 result.setConfig((String) configAddrContent); 059 } 060 else if (configAddrContent instanceof byte[]) 061 { 062 byte[] config = (byte[]) configAddrContent; 063 064 result.setConfigurationFactory(Objects.<DatabaseClusterConfigurationFactory<Z, D>>deserialize(config)); 065 } 066 067 RefAddr userAddr = reference.get(USER); 068 if (userAddr != null) 069 { 070 Object userAddrContent = userAddr.getContent(); 071 if (userAddrContent instanceof String) 072 { 073 result.setUser((String) userAddrContent); 074 } 075 } 076 077 RefAddr passwordAddr = reference.get(USER); 078 if (passwordAddr != null) 079 { 080 Object passwordAddrContent = passwordAddr.getContent(); 081 if (passwordAddrContent instanceof String) 082 { 083 result.setPassword((String) passwordAddrContent); 084 } 085 } 086 087 return result; 088 } 089}