DelegatingContext implements Context { public void close() throws NamingException { final Context context = this.getInnermostDelegateContext(); if (context == null) { return; } this.delegateContext = null; try { boolean valid = true; if (context instanceof FailureAwareContext) { FailureAwareContext failureAwareContext = (FailureAwareContext) context; if(failureAwareContext.hasFailed()) { valid = false; } } if (valid) { this.keyedObjectPool.returnObject(this.dirContextType, context); } else { this.keyedObjectPool.invalidateObject(this.dirContextType, context); } } catch (Exception e) { final NamingException namingException = new NamingException("Failed to return delegate Context to pool."); namingException.setRootCause(e); throw namingException; } finally { this.keyedObjectPool = null; } } DelegatingContext(KeyedObjectPool<Object,Object> keyedObjectPool, Context delegateContext, DirContextType dirContextType); Context getDelegateContext(); Context getInnermostDelegateContext(); boolean equals(Object obj); int hashCode(); String toString(); Object addToEnvironment(String propName, Object propVal); void bind(Name name, Object obj); void bind(String name, Object obj); void close(); Name composeName(Name name, Name prefix); String composeName(String name, String prefix); Context createSubcontext(Name name); Context createSubcontext(String name); void destroySubcontext(Name name); void destroySubcontext(String name); Hashtable<?, ?> getEnvironment(); String getNameInNamespace(); NameParser getNameParser(Name name); NameParser getNameParser(String name); NamingEnumeration<NameClassPair> list(Name name); NamingEnumeration<NameClassPair> list(String name); NamingEnumeration<Binding> listBindings(Name name); NamingEnumeration<Binding> listBindings(String name); Object lookup(Name name); Object lookup(String name); Object lookupLink(Name name); Object lookupLink(String name); void rebind(Name name, Object obj); void rebind(String name, Object obj); Object removeFromEnvironment(String propName); void rename(Name oldName, Name newName); void rename(String oldName, String newName); void unbind(Name name); void unbind(String name);  }
@Test public void testDoubleClose() throws Exception { final DelegatingContext delegatingContext = new DelegatingContext( keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); delegatingContext.close(); delegatingContext.close(); verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, contextMock); }
@Test public void testPoolExceptionOnClose() throws Exception { doThrow(new Exception("Fake Pool returnObject Exception")) .when(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); final DelegatingContext delegatingContext = new DelegatingContext( keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); try { delegatingContext.close(); fail("DelegatingContext.close should have thrown a NamingException"); } catch (NamingException ne) { } }