1 23 24 package com.rift.coad.lib.naming; 26 27 import org.apache.log4j.Logger; 29 30 import java.util.StringTokenizer ; 32 import javax.naming.Context ; 33 import javax.naming.InitialContext ; 34 import javax.naming.CompositeName ; 35 36 41 public class ContextManager { 42 43 protected Logger log = 45 Logger.getLogger(ContextManager.class.getName()); 46 47 private Context baseContext = null; 49 private String base = null; 50 private String contextPath = null; 51 52 58 public ContextManager(String base) throws NamingException { 59 this.base = base; 60 if (base.endsWith("/")) { 61 this.base = base.substring(0,base.length() - 1); 62 } 63 baseContext = initContext(this.base); 64 } 65 66 67 74 public void bind(String name, Object ref) throws NamingException { 75 try { 76 if (ref == null) { 77 throw new NamingException("The reference to bind is null"); 78 } 79 String bindName = name; 80 if (contextPath != null) { 81 bindName = contextPath + "/" + name; 82 } 83 log.info("Binding [" + bindName + "]"); 84 baseContext.bind(bindName,ref); 85 } catch (NamingException ex) { 86 throw ex; 87 } catch (Exception ex) { 88 log.error("Failed to bind to the context : " + ex.getMessage(),ex); 89 throw new NamingException( 90 "Failed to bind the object to the context : " + 91 ex.getMessage(),ex); 92 } 93 } 94 95 96 102 public void unbind(String name) throws NamingException { 103 try { 104 String bindName = name; 105 if (contextPath != null) { 106 bindName = contextPath + "/" + name; 107 } 108 baseContext.unbind(bindName); 109 log.info("Un-bound [" + base + "/" + name + "]"); 110 } catch (Exception ex) { 111 log.error("Failed to unbind to the context : " + ex.getMessage(),ex); 112 throw new NamingException( 113 "Failed to unbind the object to the context : " + 114 ex.getMessage(),ex); 115 } 116 } 117 118 119 125 private Context initContext(String base) throws NamingException { 126 try { 127 Context context = new InitialContext (); 128 StringTokenizer stringTok = new StringTokenizer (base,"/"); 129 while(stringTok.hasMoreTokens()) { 130 String entry = stringTok.nextToken(); 131 Context subContext = null; 132 try { 133 subContext = (Context )context.lookup(entry); 134 } catch (Exception exc) { 135 } finally { 137 if (subContext == null) { 138 try { 139 subContext = context.createSubcontext(entry); 140 } catch (javax.naming.OperationNotSupportedException ex) { 141 contextPath = base; 144 return context; 145 } catch (javax.naming.NameAlreadyBoundException ex) { 146 contextPath = base; 147 return context; 148 } 149 } 150 } 151 context = subContext; 152 } 153 return context; 154 } catch (Exception ex) { 155 log.error("Failed to init the context : " + ex.getMessage(),ex); 156 throw new NamingException("Failed to init the context : " + 157 ex.getMessage(),ex); 158 } 159 } 160 } 161 | Popular Tags |