1 6 7 package org.jfox.jndi.enc; 8 9 import java.util.Hashtable ; 10 import javax.naming.Context ; 11 import javax.naming.Name ; 12 import javax.naming.spi.ObjectFactory ; 13 14 17 18 public class EnterpriseContextFactory implements ObjectFactory { 19 public final static EnterpriseType WEB = new EnterpriseType("web"); 20 public final static EnterpriseType EJB = new EnterpriseType("ejb"); 21 22 public final static String ENC_JNDI_NAME = "java:comp/env"; 23 24 27 private static ThreadLocal tl = new ThreadLocal (); 28 private final static String WEB_ENC_OBJECT_FACTORY_CLASS = "org.jfox.deployment.web.WebEnterpriseContextFactory"; 29 private final static String EJB_ENC_OBJECT_FACTORY_CLASS = "org.jfox.ejb.naming.EJBEnterpriseContextFactory"; 30 31 public static EnterpriseType enterWeb() { 32 EnterpriseType type = (EnterpriseType) tl.get(); 33 tl.set(WEB); 34 return type; 35 } 36 37 public static EnterpriseType enterEjb() { 38 EnterpriseType type = (EnterpriseType) tl.get(); 39 tl.set(EJB); 40 return type; 41 } 42 43 public static void enter(EnterpriseType type) { 44 tl.set(type); 45 } 46 47 public static boolean isEnterpriseContext(Name name) { 48 if(name.toString().startsWith(ENC_JNDI_NAME) && name.toString().length() > (ENC_JNDI_NAME.length() + 1)) { 49 return true; 50 } 51 return false; 52 } 53 54 public static Name getEnterpriseContextSuffix(Name name) { 55 if(isEnterpriseContext(name)) { 56 return name.getSuffix(2); 57 } 58 else { 59 return name; 60 } 61 } 62 63 public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { 64 EnterpriseType type = (EnterpriseType) tl.get(); 65 if(type.equals(WEB)) { 66 ObjectFactory of = (ObjectFactory ) Thread.currentThread().getContextClassLoader().loadClass(WEB_ENC_OBJECT_FACTORY_CLASS).newInstance(); 67 return of.getObjectInstance(obj, name, nameCtx, environment); 68 } 69 else if(type.equals(EJB)) { 70 ObjectFactory of = (ObjectFactory ) Thread.currentThread().getContextClassLoader().loadClass(EJB_ENC_OBJECT_FACTORY_CLASS).newInstance(); 71 return of.getObjectInstance(obj, name, nameCtx, environment); 72 } 73 else { 74 throw new RuntimeException ("can only use java:comp/env in ejb or web application"); 75 } 76 77 } 78 79 public static class EnterpriseType { 80 81 private String type = "ejb"; 82 83 public EnterpriseType(String type) { 84 this.type = type; 85 } 86 87 public String getType() { 88 return type; 89 } 90 91 public boolean equals(Object obj) { 92 return type.equals(((EnterpriseType) obj).type); 93 } 94 95 public int hashCode() { 96 return type.hashCode(); 97 } 98 } 99 100 public static void main(String [] args) { 101 102 } 103 } 104 | Popular Tags |