From 1ba9c4316ed7e368f8d0c32e71a6f2fde5669d77 Mon Sep 17 00:00:00 2001
From: ludovicp <ludovicp@localhost>
Date: Mon, 31 May 2010 12:48:19 +0000
Subject: [PATCH] Fix for issue #4536. Close JNDI enumerations to avoid unbinding and closing underlying LDAP connection. Fixes in all CLI and control panel.

---
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/RemoteSchemaLoader.java       |   10 
 opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/installer/Installer.java                    |   21 
 opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContextHelper.java                               |   35 +
 opendj-sdk/opends/src/ads/org/opends/admin/ads/TopologyCache.java                                  |    8 
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteSchemaElementsTask.java |   41 +
 opendj-sdk/opends/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java         |   20 
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/ConfigFromDirContext.java     |   26 
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/LDAPEntryReader.java          |   10 
 opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/util/Utils.java                             |   23 
 opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContext.java                                     |  175 ++++++-
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteEntryTask.java          |   21 
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java    |   23 
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/browser/NodeRefresher.java         |  271 +++++++-----
 opendj-sdk/opends/src/ads/org/opends/admin/ads/ServerDescriptor.java                               |  413 +++++++++++-------
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java         |   10 
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/AddToGroupTask.java           |   69 +-
 opendj-sdk/opends/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java        |   30 +
 opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/datamodel/CustomSearchResult.java  |   29 
 18 files changed, 813 insertions(+), 422 deletions(-)

diff --git a/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContext.java b/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContext.java
index 0fd62b4..a8b0fba 100644
--- a/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContext.java
+++ b/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContext.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2007-2009 Sun Microsystems, Inc.
+ *      Copyright 2007-2010 Sun Microsystems, Inc.
  */
 
 package org.opends.admin.ads;
@@ -604,9 +604,9 @@
     }
 
     // Unregister the server in server groups
+    NamingEnumeration<SearchResult> ne = null;
     try
     {
-      NamingEnumeration<SearchResult> ne;
       SearchControls sc = new SearchControls();
 
       String serverID = getServerID(serverProperties);
@@ -623,24 +623,38 @@
           BasicAttribute newAttr = new BasicAttribute(memberAttrName);
           NamingEnumeration<? extends Attribute> attrs =
             sr.getAttributes().getAll();
-          while (attrs.hasMore())
+          try
           {
-            Attribute attr = attrs.next();
-            String attrID = attr.getID();
-
-            if (attrID.equalsIgnoreCase(memberAttrName))
+            while (attrs.hasMore())
             {
-              NamingEnumeration<?> ae = attr.getAll();
-              while (ae.hasMore())
+              Attribute attr = attrs.next();
+              String attrID = attr.getID();
+
+              if (attrID.equalsIgnoreCase(memberAttrName))
               {
-                String value = (String)ae.next();
-                if (!value.equalsIgnoreCase("cn="+serverID))
+                NamingEnumeration<?> ae = attr.getAll();
+                try
                 {
-                  newAttr.add(value);
+                  while (ae.hasMore())
+                  {
+                    String value = (String)ae.next();
+                    if (!value.equalsIgnoreCase("cn="+serverID))
+                    {
+                      newAttr.add(value);
+                    }
+                  }
+                }
+                finally
+                {
+                  handleCloseNamingEnumeration(ae);
                 }
               }
             }
           }
+          finally
+          {
+            handleCloseNamingEnumeration(attrs);
+          }
           BasicAttributes newAttrs = new BasicAttributes();
           newAttrs.put(newAttr);
           if (newAttr.size() > 0)
@@ -671,6 +685,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(ne);
+    }
   }
 
   /**
@@ -750,19 +768,20 @@
         + getServerGroupContainerDN());
 
     Set<String> result = new HashSet<String>() ;
+    NamingEnumeration<SearchResult> srs = null;
+    NamingEnumeration<? extends Attribute> ne = null;
     try
     {
       SearchControls sc = new SearchControls();
       sc.setSearchScope(SearchControls.OBJECT_SCOPE);
-      NamingEnumeration<SearchResult> srs = getDirContext().search(dn,
-          "(objectclass=*)", sc);
+      srs = getDirContext().search(dn, "(objectclass=*)", sc);
 
       if (!srs.hasMore())
       {
         return result;
       }
       Attributes attrs = srs.next().getAttributes();
-      NamingEnumeration<? extends Attribute> ne = attrs.getAll();
+      ne = attrs.getAll();
       while (ne.hasMore())
       {
         Attribute attr = (Attribute)ne.next();
@@ -776,9 +795,16 @@
 
         // We have the members list
         NamingEnumeration<?> ae = attr.getAll();
-        while (ae.hasMore())
+        try
         {
-          result.add((String)ae.next());
+          while (ae.hasMore())
+          {
+            result.add((String)ae.next());
+          }
+        }
+        finally
+        {
+          handleCloseNamingEnumeration(ae);
         }
         break;
       }
@@ -797,8 +823,13 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(srs);
+      handleCloseNamingEnumeration(ne);
+    }
     return result;
-      }
+  }
 
   /**
    * Returns a set containing the servers that are registered in the
@@ -814,9 +845,9 @@
   {
     Set<Map<ServerProperty,Object>> result =
       new HashSet<Map<ServerProperty,Object>>();
+    NamingEnumeration<SearchResult> ne = null;
     try
     {
-      NamingEnumeration<SearchResult> ne;
       SearchControls sc = new SearchControls();
 
       sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
@@ -829,6 +860,7 @@
         Object keyId = properties.get(ServerProperty.INSTANCE_KEY_ID);
         if (keyId != null)
         {
+          NamingEnumeration<SearchResult> ne2 = null;
           try
           {
             SearchControls sc1 = new SearchControls();
@@ -836,8 +868,7 @@
             final String attrIDs[] = { "ds-cfg-public-key-certificate;binary" };
             sc1.setReturningAttributes(attrIDs);
 
-            NamingEnumeration<SearchResult> ne2 = dirContext.search(
-                getInstanceKeysContainerDN(),
+            ne2 = dirContext.search(getInstanceKeysContainerDN(),
                 "(ds-cfg-key-id="+keyId+")", sc);
             if (ne2.hasMore())
             {
@@ -856,6 +887,10 @@
           {
             LOG.log(Level.WARNING, "Could not find public key for "+properties);
           }
+          finally
+          {
+            handleCloseNamingEnumeration(ne2);
+          }
         }
         result.add(properties);
       }
@@ -875,6 +910,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(ne);
+    }
 
     return result;
   }
@@ -1038,9 +1077,9 @@
   {
     Set<Map<ServerGroupProperty, Object>> result =
       new HashSet<Map<ServerGroupProperty, Object>>();
+    NamingEnumeration<SearchResult> ne = null;
     try
     {
-      NamingEnumeration<SearchResult> ne;
       SearchControls sc = new SearchControls();
 
       sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
@@ -1069,6 +1108,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(ne);
+    }
     return result;
   }
 
@@ -1083,8 +1126,8 @@
   {
     Set<Map<AdministratorProperty, Object>> result =
       new HashSet<Map<AdministratorProperty, Object>>();
+    NamingEnumeration<SearchResult> ne = null;
     try {
-      NamingEnumeration<SearchResult> ne;
       SearchControls sc = new SearchControls();
 
       sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
@@ -1119,6 +1162,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(ne);
+    }
 
     return result;
   }
@@ -1339,6 +1386,8 @@
 
     boolean updatePassword = adminProperties
     .containsKey(AdministratorProperty.PASSWORD);
+
+    NamingEnumeration<?> currentPrivileges = null;
     try
     {
       // Entry renaming
@@ -1355,7 +1404,6 @@
 
       // if modification includes 'privilege', we have to get first the
       // current privileges list.
-      NamingEnumeration<?> currentPrivileges = null;
       if (adminProperties.containsKey(AdministratorProperty.PRIVILEGE))
       {
         SearchControls sc = new SearchControls();
@@ -1370,6 +1418,7 @@
         .getAll();
       }
 
+
       // Replace properties, if needed.
       if (adminProperties.size() > 1)
       {
@@ -1395,6 +1444,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(currentPrivileges);
+    }
   }
 
   /**
@@ -1795,9 +1848,16 @@
 
           Set<String> set = new HashSet<String>();
           NamingEnumeration<?> ae = attr.getAll();
-          while (ae.hasMore())
+          try
           {
-            set.add((String)ae.next());
+            while (ae.hasMore())
+            {
+              set.add((String)ae.next());
+            }
+          }
+          finally
+          {
+            ae.close();
           }
           value = set;
         }
@@ -1863,9 +1923,16 @@
           {
             Set<String> set = new HashSet<String>();
             NamingEnumeration<?> ae = attr.getAll();
-            while (ae.hasMore())
+            try
             {
-              set.add((String)ae.next());
+              while (ae.hasMore())
+              {
+                set.add((String)ae.next());
+              }
+            }
+            finally
+            {
+              ae.close();
             }
             value = set;
           }
@@ -1884,7 +1951,7 @@
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
     return result;
-      }
+  }
 
 
   /**
@@ -1906,10 +1973,10 @@
     nameObj = nameFromDN(rdn);
     String dn = nameObj + "," + getAdministratorContainerDN();
     result.put(AdministratorProperty.ADMINISTRATOR_DN, dn);
-
+    NamingEnumeration<? extends Attribute> ne = null;
     try
     {
-      NamingEnumeration<? extends Attribute> ne = attrs.getAll();
+      ne = attrs.getAll();
       while (ne.hasMore()) {
         Attribute attr = ne.next();
         String attrID = attr.getID();
@@ -1947,6 +2014,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, x);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(ne);
+    }
 
     return result;
   }
@@ -2430,13 +2501,24 @@
       searchControls.setReturningAttributes(attrIDs);
       NamingEnumeration<SearchResult> keyEntries
       = dirContext.search(baseDN, searchFilter, searchControls);
-      while (keyEntries.hasMore()) {
-        final SearchResult entry = keyEntries.next();
-        final Attributes attrs = entry.getAttributes();
-        final Attribute keyIDAttr = attrs.get(attrIDs[0]);
-        final Attribute keyCertAttr = attrs.get(attrIDs[1]);
-        if (null == keyIDAttr || null == keyCertAttr) continue; // schema viol.
-        certificateMap.put((String)keyIDAttr.get(), (byte[])keyCertAttr.get());
+      try
+      {
+        while (keyEntries.hasMore()) {
+          final SearchResult entry = keyEntries.next();
+          final Attributes attrs = entry.getAttributes();
+          final Attribute keyIDAttr = attrs.get(attrIDs[0]);
+          final Attribute keyCertAttr = attrs.get(attrIDs[1]);
+          if (null == keyIDAttr || null == keyCertAttr)
+          {
+            continue;// schema viol.
+          }
+          certificateMap.put((String)keyIDAttr.get(),
+              (byte[])keyCertAttr.get());
+        }
+      }
+      finally
+      {
+        keyEntries.close();
       }
     }
     catch (NamingException x) {
@@ -2581,4 +2663,21 @@
       }
     }
   }
+
+  private void handleCloseNamingEnumeration(NamingEnumeration<?> ne)
+  throws ADSContextException
+  {
+    if (ne != null)
+    {
+      try
+      {
+        ne.close();
+      }
+      catch (NamingException ex)
+      {
+        throw new ADSContextException(
+            ADSContextException.ErrorType.ERROR_UNEXPECTED, ex);
+      }
+    }
+  }
 }
diff --git a/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContextHelper.java b/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContextHelper.java
index 0caafed..fe9fcaa 100644
--- a/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContextHelper.java
+++ b/opendj-sdk/opends/src/ads/org/opends/admin/ads/ADSContextHelper.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2007-2009 Sun Microsystems, Inc.
+ *      Copyright 2007-2010 Sun Microsystems, Inc.
  */
 
 package org.opends.admin.ads;
@@ -232,10 +232,11 @@
 
     /* search for public-key certificate entry in ADS DIT */
     final String attrIDs[] = { "ds-cfg-key-id" };
+    NamingEnumeration<SearchResult> results = null;
     try
     {
-      final NamingEnumeration<SearchResult> results = ctx.search(
-          ADSContext.getInstanceKeysContainerDN(), keyAttrs, attrIDs);
+     results = ctx.search(ADSContext.getInstanceKeysContainerDN(), keyAttrs,
+         attrIDs);
       if (results.hasMore()) {
         final Attribute keyIdAttr =
           results.next().getAttributes().get(attrIDs[0]);
@@ -287,6 +288,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, cme);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(results);
+    }
   }
 
 
@@ -324,9 +329,10 @@
 
     /* search for public-key certificate entry in ADS DIT */
     final String attrIDs[] = { "ds-cfg-key-id" };
+    NamingEnumeration<SearchResult> results = null;
     try
     {
-      final NamingEnumeration<SearchResult> results = ctx.search(
+      results = ctx.search(
           ADSContext.getInstanceKeysContainerDN(), keyAttrs, attrIDs);
       if (results.hasMore()) {
         SearchResult res = results.next();
@@ -341,6 +347,10 @@
       throw new ADSContextException(
           ADSContextException.ErrorType.ERROR_UNEXPECTED, ne);
     }
+    finally
+    {
+      handleCloseNamingEnumeration(results);
+    }
   }
 
   /**
@@ -364,4 +374,21 @@
   {
     return ConfigConstants.ATTR_CRYPTO_KEY_COMPROMISED_TIME;
   }
+
+  private void handleCloseNamingEnumeration(NamingEnumeration<?> ne)
+  throws ADSContextException
+  {
+    if (ne != null)
+    {
+      try
+      {
+        ne.close();
+      }
+      catch (NamingException ex)
+      {
+        throw new ADSContextException(
+            ADSContextException.ErrorType.ERROR_UNEXPECTED, ex);
+      }
+    }
+  }
 }
diff --git a/opendj-sdk/opends/src/ads/org/opends/admin/ads/ServerDescriptor.java b/opendj-sdk/opends/src/ads/org/opends/admin/ads/ServerDescriptor.java
index c02efca..c578579 100644
--- a/opendj-sdk/opends/src/ads/org/opends/admin/ads/ServerDescriptor.java
+++ b/opendj-sdk/opends/src/ads/org/opends/admin/ads/ServerDescriptor.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2007-2009 Sun Microsystems, Inc.
+ *      Copyright 2007-2010 Sun Microsystems, Inc.
  */
 
 package org.opends.admin.ads;
@@ -335,9 +335,9 @@
 
     if (!serverProperties.isEmpty())
     {
-      ArrayList s = (ArrayList)serverProperties.get(
+      ArrayList<?> s = (ArrayList<?>)serverProperties.get(
           ServerProperty.LDAP_ENABLED);
-      ArrayList p = (ArrayList)serverProperties.get(
+      ArrayList<?> p = (ArrayList<?>)serverProperties.get(
           ServerProperty.LDAP_PORT);
       if (s != null)
       {
@@ -372,9 +372,9 @@
 
     if (!serverProperties.isEmpty())
     {
-      ArrayList s = (ArrayList)serverProperties.get(
+      ArrayList<?> s = (ArrayList<?>)serverProperties.get(
           ServerProperty.LDAPS_ENABLED);
-      ArrayList p = (ArrayList)serverProperties.get(
+      ArrayList<?> p = (ArrayList<?>)serverProperties.get(
           ServerProperty.LDAPS_PORT);
       if (s != null)
       {
@@ -409,9 +409,9 @@
 
     if (!serverProperties.isEmpty())
     {
-      ArrayList s = (ArrayList)serverProperties.get(
+      ArrayList<?> s = (ArrayList<?>)serverProperties.get(
           ServerProperty.ADMIN_ENABLED);
-      ArrayList p = (ArrayList)serverProperties.get(
+      ArrayList<?> p = (ArrayList<?>)serverProperties.get(
           ServerProperty.ADMIN_PORT);
       if (s != null)
       {
@@ -439,9 +439,9 @@
   public List<Integer> getEnabledAdministrationPorts()
   {
     List<Integer> ports = new ArrayList<Integer>(1);
-    ArrayList s = (ArrayList)serverProperties.get(
+    ArrayList<?> s = (ArrayList<?>)serverProperties.get(
         ServerProperty.ADMIN_ENABLED);
-    ArrayList p = (ArrayList)serverProperties.get(
+    ArrayList<?> p = (ArrayList<?>)serverProperties.get(
         ServerProperty.ADMIN_PORT);
     if (s != null)
     {
@@ -471,9 +471,9 @@
 
     if (!serverProperties.isEmpty())
     {
-      ArrayList s = (ArrayList)serverProperties.get(
+      ArrayList<?> s = (ArrayList<?>)serverProperties.get(
           ServerProperty.LDAP_ENABLED);
-      ArrayList p = (ArrayList)serverProperties.get(
+      ArrayList<?> p = (ArrayList<?>)serverProperties.get(
           ServerProperty.LDAP_PORT);
       if (s != null)
       {
@@ -488,9 +488,9 @@
       }
       if (securePreferred)
       {
-        s = (ArrayList)serverProperties.get(
+        s = (ArrayList<?>)serverProperties.get(
             ServerProperty.ADMIN_ENABLED);
-        p = (ArrayList)serverProperties.get(ServerProperty.ADMIN_PORT);
+        p = (ArrayList<?>)serverProperties.get(ServerProperty.ADMIN_PORT);
         if (s != null)
         {
           for (int i=0; i<s.size(); i++)
@@ -587,7 +587,7 @@
           ServerProperty.ADMIN_ENABLED
       };
       for (ServerProperty prop : props) {
-        ArrayList s = (ArrayList) serverProperties.get(prop);
+        ArrayList<?> s = (ArrayList<?>) serverProperties.get(prop);
         for (Object o : s) {
           buf.append(":").append(o);
         }
@@ -694,8 +694,8 @@
 
     for (int i=0; i<sProps.length; i++)
     {
-      ArrayList s = (ArrayList)serverProperties.get(sProps[i][0]);
-      ArrayList p = (ArrayList)serverProperties.get(sProps[i][1]);
+      ArrayList<?> s = (ArrayList<?>)serverProperties.get(sProps[i][0]);
+      ArrayList<?> p = (ArrayList<?>)serverProperties.get(sProps[i][1]);
       if (s != null)
       {
         int port = -1;
@@ -723,7 +723,7 @@
       }
     }
 
-    ArrayList array = (ArrayList)serverProperties.get(
+    ArrayList<?> array = (ArrayList<?>)serverProperties.get(
         ServerProperty.STARTTLS_ENABLED);
     boolean startTLSEnabled = false;
     if ((array != null) && !array.isEmpty())
@@ -802,44 +802,53 @@
     String filter = "(objectclass=ds-cfg-ldap-connection-handler)";
 
     LdapName jndiName = new LdapName("cn=config");
-    NamingEnumeration listeners = ctx.search(jndiName, filter, ctls);
+    NamingEnumeration<SearchResult> listeners =
+      ctx.search(jndiName, filter, ctls);
 
-    ArrayList<Integer> ldapPorts = new ArrayList<Integer>();
-    ArrayList<Integer> ldapsPorts = new ArrayList<Integer>();
-    ArrayList<Boolean> ldapEnabled = new ArrayList<Boolean>();
-    ArrayList<Boolean> ldapsEnabled = new ArrayList<Boolean>();
-    ArrayList<Boolean> startTLSEnabled = new ArrayList<Boolean>();
-
-    desc.serverProperties.put(ServerProperty.LDAP_PORT, ldapPorts);
-    desc.serverProperties.put(ServerProperty.LDAPS_PORT, ldapsPorts);
-    desc.serverProperties.put(ServerProperty.LDAP_ENABLED, ldapEnabled);
-    desc.serverProperties.put(ServerProperty.LDAPS_ENABLED, ldapsEnabled);
-    desc.serverProperties.put(ServerProperty.STARTTLS_ENABLED, startTLSEnabled);
-
-    while(listeners.hasMore())
+    try
     {
-      SearchResult sr = (SearchResult)listeners.next();
+      ArrayList<Integer> ldapPorts = new ArrayList<Integer>();
+      ArrayList<Integer> ldapsPorts = new ArrayList<Integer>();
+      ArrayList<Boolean> ldapEnabled = new ArrayList<Boolean>();
+      ArrayList<Boolean> ldapsEnabled = new ArrayList<Boolean>();
+      ArrayList<Boolean> startTLSEnabled = new ArrayList<Boolean>();
 
-      String port = getFirstValue(sr, "ds-cfg-listen-port");
+      desc.serverProperties.put(ServerProperty.LDAP_PORT, ldapPorts);
+      desc.serverProperties.put(ServerProperty.LDAPS_PORT, ldapsPorts);
+      desc.serverProperties.put(ServerProperty.LDAP_ENABLED, ldapEnabled);
+      desc.serverProperties.put(ServerProperty.LDAPS_ENABLED, ldapsEnabled);
+      desc.serverProperties.put(ServerProperty.STARTTLS_ENABLED,
+          startTLSEnabled);
 
-      boolean isSecure = "true".equalsIgnoreCase(
-          getFirstValue(sr, "ds-cfg-use-ssl"));
+      while(listeners.hasMore())
+      {
+        SearchResult sr = listeners.next();
 
-      boolean enabled = "true".equalsIgnoreCase(
+        String port = getFirstValue(sr, "ds-cfg-listen-port");
+
+        boolean isSecure = "true".equalsIgnoreCase(
+            getFirstValue(sr, "ds-cfg-use-ssl"));
+
+        boolean enabled = "true".equalsIgnoreCase(
             getFirstValue(sr, "ds-cfg-enabled"));
-      if (isSecure)
-      {
-        ldapsPorts.add(new Integer(port));
-        ldapsEnabled.add(enabled);
+        if (isSecure)
+        {
+          ldapsPorts.add(new Integer(port));
+          ldapsEnabled.add(enabled);
+        }
+        else
+        {
+          ldapPorts.add(new Integer(port));
+          ldapEnabled.add(enabled);
+          enabled = "true".equalsIgnoreCase(
+              getFirstValue(sr, "ds-cfg-allow-start-tls"));
+          startTLSEnabled.add(enabled);
+        }
       }
-      else
-      {
-        ldapPorts.add(new Integer(port));
-        ldapEnabled.add(enabled);
-        enabled = "true".equalsIgnoreCase(
-            getFirstValue(sr, "ds-cfg-allow-start-tls"));
-        startTLSEnabled.add(enabled);
-      }
+    }
+    finally
+    {
+      listeners.close();
     }
   }
 
@@ -857,28 +866,36 @@
     String filter = "(objectclass=ds-cfg-administration-connector)";
 
     LdapName jndiName = new LdapName("cn=config");
-    NamingEnumeration listeners = ctx.search(jndiName, filter, ctls);
+    NamingEnumeration<SearchResult> listeners =
+      ctx.search(jndiName, filter, ctls);
 
-    Integer adminConnectorPort = null;
-
-    // we should have a single administration connector
-    if (listeners.hasMore()) {
-      SearchResult sr = (SearchResult) listeners.next();
-      String port = getFirstValue(sr, "ds-cfg-listen-port");
-      adminConnectorPort = new Integer(port);
-    }
-
-    // Even if we have a single port, use an array to be consistent with
-    // other protocols.
-    ArrayList<Integer> adminPorts = new ArrayList<Integer>();
-    ArrayList<Boolean> adminEnabled = new ArrayList<Boolean>();
-    if (adminConnectorPort != null)
+    try
     {
-      adminPorts.add(adminConnectorPort);
-      adminEnabled.add(Boolean.TRUE);
+      Integer adminConnectorPort = null;
+
+      // we should have a single administration connector
+      if (listeners.hasMore()) {
+        SearchResult sr = listeners.next();
+        String port = getFirstValue(sr, "ds-cfg-listen-port");
+        adminConnectorPort = new Integer(port);
+      }
+
+      // Even if we have a single port, use an array to be consistent with
+      // other protocols.
+      ArrayList<Integer> adminPorts = new ArrayList<Integer>();
+      ArrayList<Boolean> adminEnabled = new ArrayList<Boolean>();
+      if (adminConnectorPort != null)
+      {
+        adminPorts.add(adminConnectorPort);
+        adminEnabled.add(Boolean.TRUE);
+      }
+      desc.serverProperties.put(ServerProperty.ADMIN_PORT, adminPorts);
+      desc.serverProperties.put(ServerProperty.ADMIN_ENABLED, adminEnabled);
     }
-    desc.serverProperties.put(ServerProperty.ADMIN_PORT, adminPorts);
-    desc.serverProperties.put(ServerProperty.ADMIN_ENABLED, adminEnabled);
+    finally
+    {
+      listeners.close();
+    }
   }
 
   private static void updateJmxConfiguration(ServerDescriptor desc,
@@ -898,7 +915,8 @@
     String filter = "(objectclass=ds-cfg-jmx-connection-handler)";
 
     LdapName jndiName = new LdapName("cn=config");
-    NamingEnumeration listeners = ctx.search(jndiName, filter, ctls);
+    NamingEnumeration<SearchResult> listeners =
+      ctx.search(jndiName, filter, ctls);
 
     ArrayList<Integer> jmxPorts = new ArrayList<Integer>();
     ArrayList<Integer> jmxsPorts = new ArrayList<Integer>();
@@ -910,27 +928,34 @@
     desc.serverProperties.put(ServerProperty.JMX_ENABLED, jmxEnabled);
     desc.serverProperties.put(ServerProperty.JMXS_ENABLED, jmxsEnabled);
 
-    while(listeners.hasMore())
+    try
     {
-      SearchResult sr = (SearchResult)listeners.next();
+      while(listeners.hasMore())
+      {
+        SearchResult sr = listeners.next();
 
-      String port = getFirstValue(sr, "ds-cfg-listen-port");
+        String port = getFirstValue(sr, "ds-cfg-listen-port");
 
-      boolean isSecure = "true".equalsIgnoreCase(
-          getFirstValue(sr, "ds-cfg-use-ssl"));
+        boolean isSecure = "true".equalsIgnoreCase(
+            getFirstValue(sr, "ds-cfg-use-ssl"));
 
-      boolean enabled = "true".equalsIgnoreCase(
+        boolean enabled = "true".equalsIgnoreCase(
             getFirstValue(sr, "ds-cfg-enabled"));
-      if (isSecure)
-      {
-        jmxsPorts.add(new Integer(port));
-        jmxsEnabled.add(enabled);
+        if (isSecure)
+        {
+          jmxsPorts.add(new Integer(port));
+          jmxsEnabled.add(enabled);
+        }
+        else
+        {
+          jmxPorts.add(new Integer(port));
+          jmxEnabled.add(enabled);
+        }
       }
-      else
-      {
-        jmxPorts.add(new Integer(port));
-        jmxEnabled.add(enabled);
-      }
+    }
+    finally
+    {
+      listeners.close();
     }
   }
 
@@ -952,82 +977,90 @@
     String filter = "(objectclass=ds-cfg-backend)";
 
     LdapName jndiName = new LdapName("cn=config");
-    NamingEnumeration databases = ctx.search(jndiName, filter, ctls);
+    NamingEnumeration<SearchResult> databases =
+      ctx.search(jndiName, filter, ctls);
 
-    while(databases.hasMore())
+    try
     {
-      SearchResult sr = (SearchResult)databases.next();
-
-      String id = getFirstValue(sr, "ds-cfg-backend-id");
-
-      if (!isConfigBackend(id) || isSchemaBackend(id))
+      while(databases.hasMore())
       {
-        Set<String> baseDns = getValues(sr, "ds-cfg-base-dn");
+        SearchResult sr = databases.next();
 
-        Set<String> entries;
-        if (cacheFilter.searchMonitoringInformation())
-        {
-          entries = getBaseDNEntryCount(ctx, id);
-        }
-        else
-        {
-          entries = new HashSet<String>();
-        }
+        String id = getFirstValue(sr, "ds-cfg-backend-id");
 
-        Set<ReplicaDescriptor> replicas = desc.getReplicas();
-        for (String baseDn : baseDns)
+        if (!isConfigBackend(id) || isSchemaBackend(id))
         {
-          boolean addReplica = cacheFilter.searchAllBaseDNs();
-          if (!addReplica)
+          Set<String> baseDns = getValues(sr, "ds-cfg-base-dn");
+
+          Set<String> entries;
+          if (cacheFilter.searchMonitoringInformation())
           {
-            for (String dn : cacheFilter.getBaseDNsToSearch())
-            {
-              addReplica = Utils.areDnsEqual(dn, baseDn);
-              if (addReplica)
-              {
-                break;
-              }
-            }
+            entries = getBaseDNEntryCount(ctx, id);
           }
-          if(addReplica)
+          else
           {
-            SuffixDescriptor suffix = new SuffixDescriptor();
-            suffix.setDN(baseDn);
-            ReplicaDescriptor replica = new ReplicaDescriptor();
-            replica.setServer(desc);
-            replica.setBackendName(id);
-            replicas.add(replica);
-            HashSet<ReplicaDescriptor> r = new HashSet<ReplicaDescriptor>();
-            r.add(replica);
-            suffix.setReplicas(r);
-            replica.setSuffix(suffix);
-            int nEntries = -1;
-            for (String s : entries)
+            entries = new HashSet<String>();
+          }
+
+          Set<ReplicaDescriptor> replicas = desc.getReplicas();
+          for (String baseDn : baseDns)
+          {
+            boolean addReplica = cacheFilter.searchAllBaseDNs();
+            if (!addReplica)
             {
-              int index = s.indexOf(" ");
-              if (index != -1)
+              for (String dn : cacheFilter.getBaseDNsToSearch())
               {
-                String dn = s.substring(index + 1);
-                if (Utils.areDnsEqual(baseDn, dn))
+                addReplica = Utils.areDnsEqual(dn, baseDn);
+                if (addReplica)
                 {
-                  try
-                  {
-                    nEntries = Integer.parseInt(s.substring(0, index));
-                  }
-                  catch (Throwable t)
-                  {
-                    /* Ignore */
-                  }
                   break;
                 }
               }
             }
-            replica.setEntries(nEntries);
+            if(addReplica)
+            {
+              SuffixDescriptor suffix = new SuffixDescriptor();
+              suffix.setDN(baseDn);
+              ReplicaDescriptor replica = new ReplicaDescriptor();
+              replica.setServer(desc);
+              replica.setBackendName(id);
+              replicas.add(replica);
+              HashSet<ReplicaDescriptor> r = new HashSet<ReplicaDescriptor>();
+              r.add(replica);
+              suffix.setReplicas(r);
+              replica.setSuffix(suffix);
+              int nEntries = -1;
+              for (String s : entries)
+              {
+                int index = s.indexOf(" ");
+                if (index != -1)
+                {
+                  String dn = s.substring(index + 1);
+                  if (Utils.areDnsEqual(baseDn, dn))
+                  {
+                    try
+                    {
+                      nEntries = Integer.parseInt(s.substring(0, index));
+                    }
+                    catch (Throwable t)
+                    {
+                      /* Ignore */
+                    }
+                    break;
+                  }
+                }
+              }
+              replica.setEntries(nEntries);
+            }
           }
+          desc.setReplicas(replicas);
         }
-        desc.setReplicas(replicas);
       }
     }
+    finally
+    {
+      databases.close();
+    }
   }
 
   private static void updateReplication(ServerDescriptor desc,
@@ -1045,14 +1078,15 @@
 
     LdapName jndiName = new LdapName(
       "cn=Multimaster Synchronization,cn=Synchronization Providers,cn=config");
+    NamingEnumeration<SearchResult> syncProviders = null;
 
     try
     {
-      NamingEnumeration syncProviders = ctx.search(jndiName, filter, ctls);
+      syncProviders = ctx.search(jndiName, filter, ctls);
 
       while(syncProviders.hasMore())
       {
-        SearchResult sr = (SearchResult)syncProviders.next();
+        SearchResult sr = syncProviders.next();
 
         if ("true".equalsIgnoreCase(getFirstValue(sr,
           "ds-cfg-enabled")))
@@ -1065,6 +1099,13 @@
     {
       /* ignore */
     }
+    finally
+    {
+      if (syncProviders != null)
+      {
+        syncProviders.close();
+      }
+    }
     desc.serverProperties.put(ServerProperty.IS_REPLICATION_ENABLED,
         replicationEnabled ? Boolean.TRUE : Boolean.FALSE);
 
@@ -1085,13 +1126,14 @@
       jndiName = new LdapName(
       "cn=Multimaster Synchronization,cn=Synchronization Providers,cn=config");
 
+      syncProviders = null;
       try
       {
-        NamingEnumeration syncProviders = ctx.search(jndiName, filter, ctls);
+        syncProviders = ctx.search(jndiName, filter, ctls);
 
         while(syncProviders.hasMore())
         {
-          SearchResult sr = (SearchResult)syncProviders.next();
+          SearchResult sr = syncProviders.next();
 
           int id = Integer.parseInt(
               getFirstValue(sr, "ds-cfg-server-id"));
@@ -1123,6 +1165,13 @@
       {
         /* ignore */
       }
+      finally
+      {
+        if (syncProviders != null)
+        {
+          syncProviders.close();
+        }
+      }
     }
 
     ctls = new SearchControls();
@@ -1139,13 +1188,14 @@
 
     desc.serverProperties.put(ServerProperty.IS_REPLICATION_SERVER,
         Boolean.FALSE);
+    NamingEnumeration<SearchResult> entries = null;
     try
     {
-      NamingEnumeration entries = ctx.search(jndiName, filter, ctls);
+      entries = ctx.search(jndiName, filter, ctls);
 
-      while(entries.hasMore())
+      while (entries.hasMore())
       {
-        SearchResult sr = (SearchResult)entries.next();
+        SearchResult sr = entries.next();
 
         desc.serverProperties.put(ServerProperty.IS_REPLICATION_SERVER,
             Boolean.TRUE);
@@ -1172,6 +1222,13 @@
     {
       /* ignore */
     }
+    finally
+    {
+      if (entries != null)
+      {
+        entries.close();
+      }
+    }
 
     boolean replicationSecure = false;
     if (replicationEnabled)
@@ -1184,14 +1241,21 @@
 
       jndiName = new LdapName("cn=Crypto Manager,cn=config");
 
-      NamingEnumeration entries = ctx.search(jndiName, filter, ctls);
+      entries = ctx.search(jndiName, filter, ctls);
 
-      while(entries.hasMore())
+      try
       {
-        SearchResult sr = (SearchResult)entries.next();
+        while (entries.hasMore())
+        {
+          SearchResult sr = entries.next();
 
-        String v = getFirstValue(sr, "ds-cfg-ssl-encryption");
-        replicationSecure = "true".equalsIgnoreCase(v);
+          String v = getFirstValue(sr, "ds-cfg-ssl-encryption");
+          replicationSecure = "true".equalsIgnoreCase(v);
+        }
+      }
+      finally
+      {
+        entries.close();
       }
     }
     desc.serverProperties.put(ServerProperty.IS_REPLICATION_SECURE,
@@ -1269,14 +1333,22 @@
     String filter = "|(objectclass=*)(objectclass=ldapsubentry)";
 
     LdapName jndiName = new LdapName("cn=schema");
-    NamingEnumeration listeners = ctx.search(jndiName, filter, ctls);
+    NamingEnumeration<SearchResult> listeners =
+      ctx.search(jndiName, filter, ctls);
 
-    while(listeners.hasMore())
+    try
     {
-      SearchResult sr = (SearchResult)listeners.next();
+      while(listeners.hasMore())
+      {
+        SearchResult sr = listeners.next();
 
-      desc.serverProperties.put(ServerProperty.SCHEMA_GENERATION_ID,
-          getFirstValue(sr, "ds-sync-generation-id"));
+        desc.serverProperties.put(ServerProperty.SCHEMA_GENERATION_ID,
+            getFirstValue(sr, "ds-sync-generation-id"));
+      }
+    }
+    finally
+    {
+      listeners.close();
     }
   }
 
@@ -1346,10 +1418,17 @@
       NamingEnumeration<SearchResult> ne = ctx.search(TRUSTSTORE_DN,
           "(objectclass=ds-cfg-instance-key)", sc);
       ArrayList<String> dnsToDelete = new ArrayList<String>();
-      while (ne.hasMore())
+      try
       {
-        SearchResult sr = ne.next();
-        dnsToDelete.add(sr.getName()+","+TRUSTSTORE_DN);
+        while (ne.hasMore())
+        {
+          SearchResult sr = ne.next();
+          dnsToDelete.add(sr.getName()+","+TRUSTSTORE_DN);
+        }
+      }
+      finally
+      {
+        ne.close();
       }
       for (String dn : dnsToDelete)
       {
@@ -1384,13 +1463,21 @@
     String filter = "(ds-backend-id="+backendID+")";
 
     LdapName jndiName = new LdapName("cn=monitor");
-    NamingEnumeration listeners = ctx.search(jndiName, filter, ctls);
+    NamingEnumeration<SearchResult> listeners =
+      ctx.search(jndiName, filter, ctls);
 
-    while(listeners.hasMore())
+    try
     {
-      SearchResult sr = (SearchResult)listeners.next();
+      while(listeners.hasMore())
+      {
+        SearchResult sr = listeners.next();
 
-      v.addAll(getValues(sr, "ds-base-dn-entry-count"));
+        v.addAll(getValues(sr, "ds-base-dn-entry-count"));
+      }
+    }
+    finally
+    {
+      listeners.close();
     }
     return v;
   }
diff --git a/opendj-sdk/opends/src/ads/org/opends/admin/ads/TopologyCache.java b/opendj-sdk/opends/src/ads/org/opends/admin/ads/TopologyCache.java
index 8d36d01..bbc5685 100644
--- a/opendj-sdk/opends/src/ads/org/opends/admin/ads/TopologyCache.java
+++ b/opendj-sdk/opends/src/ads/org/opends/admin/ads/TopologyCache.java
@@ -475,13 +475,13 @@
     LdapName jndiName = new LdapName("cn=monitor");
 
     InitialLdapContext ctx = null;
+    NamingEnumeration<SearchResult> monitorEntries = null;
     try
     {
       ServerLoader loader =
         getServerLoader(replicationServer.getAdsProperties());
       ctx = loader.createContext();
-      NamingEnumeration<SearchResult> monitorEntries =
-        ctx.search(jndiName, filter, ctls);
+      monitorEntries = ctx.search(jndiName, filter, ctls);
 
       while(monitorEntries.hasMore())
       {
@@ -537,6 +537,10 @@
     }
     finally
     {
+      if (monitorEntries != null)
+      {
+        monitorEntries.close();
+      }
       if (ctx != null)
       {
         ctx.close();
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/browser/NodeRefresher.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/browser/NodeRefresher.java
index 3123728..3d3fdda 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/browser/NodeRefresher.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/browser/NodeRefresher.java
@@ -349,10 +349,17 @@
     NamingEnumeration<SearchResult> s = ctx.search(new LdapName(node.getDN()),
               controller.getFilter(),
               ctls);
-    if (!s.hasMoreElements())
+    try
     {
-      throw new NameNotFoundException("Entry "+node.getDN()+
-          " does not verify filter "+controller.getFilter());
+      if (!s.hasMoreElements())
+      {
+        throw new NameNotFoundException("Entry "+node.getDN()+
+            " does not verify filter "+controller.getFilter());
+      }
+    }
+    finally
+    {
+      s.close();
     }
   }
 
@@ -372,10 +379,17 @@
     NamingEnumeration<SearchResult> s = ctx.search(new LdapName(dn),
               controller.getFilter(),
               ctls);
-    if (!s.hasMoreElements())
+    try
     {
-      throw new NameNotFoundException("Entry "+dn+
-          " does not verify filter "+controller.getFilter());
+      if (!s.hasMoreElements())
+      {
+        throw new NameNotFoundException("Entry "+dn+
+            " does not verify filter "+controller.getFilter());
+      }
+    }
+    finally
+    {
+      s.close();
     }
   }
 
@@ -402,11 +416,18 @@
       NamingEnumeration<SearchResult> s = ctx.search(new LdapName(node.getDN()),
                 controller.getObjectSearchFilter(),
                 ctls);
-      if (s.hasMore())
+      try
       {
-        localEntry = s.next();
-        localEntry.setName(node.getDN());
+        if (s.hasMore())
+        {
+          localEntry = s.next();
+          localEntry.setName(node.getDN());
 
+        }
+      }
+      finally
+      {
+        s.close();
       }
       if (localEntry == null) {
         /* Not enough rights to read the entry or the entry simply does not
@@ -511,23 +532,30 @@
         NamingEnumeration<SearchResult> sr = ctx.search(remoteDn,
             filter,
             ctls);
-        if (sr.hasMore())
+        try
         {
-          entry = sr.next();
-          String name;
-          if (entry.getName().length() == 0)
+          if (sr.hasMore())
           {
-            name = remoteDn;
+            entry = sr.next();
+            String name;
+            if (entry.getName().length() == 0)
+            {
+              name = remoteDn;
+            }
+            else
+            {
+              name = unquoteRelativeName(entry.getName())+","+remoteDn;
+            }
+            entry.setName(name);
           }
           else
           {
-            name = unquoteRelativeName(entry.getName())+","+remoteDn;
+            throw new NameNotFoundException();
           }
-          entry.setName(name);
         }
-        else
+        finally
         {
-          throw new NameNotFoundException();
+          sr.close();
         }
         throwAbandonIfNeeded(null);
       }
@@ -660,6 +688,17 @@
       if (ctx != null) {
         controller.releaseLDAPConnection(ctx);
       }
+      if (searchResults != null)
+      {
+        try
+        {
+          searchResults.close();
+        }
+        catch (NamingException x)
+        {
+          throwAbandonIfNeeded(x);
+        }
+      }
     }
   }
 
@@ -731,124 +770,131 @@
                 controller.getChildSearchFilter(),
                 ctls);
 
-      while (entries.hasMore())
+      try
       {
-        SearchResult r = entries.next();
-        String name;
-        if (r.getName().length() == 0)
+        while (entries.hasMore())
         {
-          continue;
-        }
-        else
-        {
-          name = unquoteRelativeName(r.getName())+","+parentDn;
-        }
-        boolean add = false;
-        if (useCustomFilter())
-        {
-          // Check that is an inmediate child: use a faster method by just
-          // comparing the number of components.
-          DN dn = null;
-          try
+          SearchResult r = entries.next();
+          String name;
+          if (r.getName().length() == 0)
           {
-            dn = DN.decode(name);
-            add = dn.getNumComponents() == parentComponents + 1;
+            continue;
           }
-          catch (Throwable t)
+          else
           {
-            throw new RuntimeException("Error decoding dns: "+t, t);
+            name = unquoteRelativeName(r.getName())+","+parentDn;
           }
-
-          if (!add)
+          boolean add = false;
+          if (useCustomFilter())
           {
-            // Is not a direct child.  Check if the parent has been added,
-            // if it is the case, do not add the parent.  If is not the case,
-            // search for the parent and add it.
-            RDN[] rdns = new RDN[parentComponents + 1];
-            int diff = dn.getNumComponents() - rdns.length;
-            for (int i=0; i < rdns.length; i++)
+            // Check that is an inmediate child: use a faster method by just
+            // comparing the number of components.
+            DN dn = null;
+            try
             {
-              rdns[i] = dn.getRDN(i + diff);
+              dn = DN.decode(name);
+              add = dn.getNumComponents() == parentComponents + 1;
             }
-            final DN parentToAddDN = new DN(rdns);
-            boolean mustAddParent = true;
-            for (SearchResult addedEntry : childEntries)
+            catch (Throwable t)
             {
-              try
+              throw new RuntimeException("Error decoding dns: "+t, t);
+            }
+
+            if (!add)
+            {
+              // Is not a direct child.  Check if the parent has been added,
+              // if it is the case, do not add the parent.  If is not the case,
+              // search for the parent and add it.
+              RDN[] rdns = new RDN[parentComponents + 1];
+              int diff = dn.getNumComponents() - rdns.length;
+              for (int i=0; i < rdns.length; i++)
               {
-                DN addedDN = DN.decode(addedEntry.getName());
-                if (addedDN.equals(parentToAddDN))
+                rdns[i] = dn.getRDN(i + diff);
+              }
+              final DN parentToAddDN = new DN(rdns);
+              boolean mustAddParent = true;
+              for (SearchResult addedEntry : childEntries)
+              {
+                try
                 {
-                  mustAddParent = false;
-                  break;
+                  DN addedDN = DN.decode(addedEntry.getName());
+                  if (addedDN.equals(parentToAddDN))
+                  {
+                    mustAddParent = false;
+                    break;
+                  }
+                }
+                catch (Throwable t)
+                {
+                  throw new RuntimeException("Error decoding dn: "+
+                      addedEntry.getName()+" . "+t, t);
                 }
               }
-              catch (Throwable t)
+              if (mustAddParent)
               {
-                throw new RuntimeException("Error decoding dn: "+
-                    addedEntry.getName()+" . "+t, t);
-              }
-            }
-            if (mustAddParent)
-            {
-              final boolean resultValue[] = {true};
-              // Check the children added to the tree
-              try
-              {
-                SwingUtilities.invokeAndWait(new Runnable()
+                final boolean resultValue[] = {true};
+                // Check the children added to the tree
+                try
                 {
-                  public void run()
+                  SwingUtilities.invokeAndWait(new Runnable()
                   {
-                    for (int i=0; i<getNode().getChildCount(); i++)
+                    public void run()
                     {
-                      BasicNode node = (BasicNode)getNode().getChildAt(i);
-                      try
+                      for (int i=0; i<getNode().getChildCount(); i++)
                       {
-                        DN dn = DN.decode(node.getDN());
-                        if (dn.equals(parentToAddDN))
+                        BasicNode node = (BasicNode)getNode().getChildAt(i);
+                        try
                         {
-                          resultValue[0] = false;
-                          break;
+                          DN dn = DN.decode(node.getDN());
+                          if (dn.equals(parentToAddDN))
+                          {
+                            resultValue[0] = false;
+                            break;
+                          }
+                        }
+                        catch (Throwable t)
+                        {
+                          throw new RuntimeException("Error decoding dn: "+
+                              node.getDN()+" . "+t, t);
                         }
                       }
-                      catch (Throwable t)
-                      {
-                        throw new RuntimeException("Error decoding dn: "+
-                            node.getDN()+" . "+t, t);
-                      }
                     }
-                  }
-                });
+                  });
+                }
+                catch (Throwable t)
+                {
+                  // Ignore
+                }
+                mustAddParent = resultValue[0];
               }
-              catch (Throwable t)
+              if (mustAddParent)
               {
-                // Ignore
+                SearchResult parentResult = searchManuallyEntry(ctx,
+                    parentToAddDN.toString());
+                childEntries.add(parentResult);
               }
-              mustAddParent = resultValue[0];
-            }
-            if (mustAddParent)
-            {
-              SearchResult parentResult = searchManuallyEntry(ctx,
-                  parentToAddDN.toString());
-              childEntries.add(parentResult);
             }
           }
-        }
-        else
-        {
-          add = true;
-        }
-        if (add)
-        {
-          r.setName(name);
-          childEntries.add(r);
-          // Time to time we update the display
-          if (childEntries.size() >= 20) {
-            changeStateTo(State.SEARCHING_CHILDREN);
-            childEntries.clear();
+          else
+          {
+            add = true;
           }
+          if (add)
+          {
+            r.setName(name);
+            childEntries.add(r);
+            // Time to time we update the display
+            if (childEntries.size() >= 20) {
+              changeStateTo(State.SEARCHING_CHILDREN);
+              childEntries.clear();
+            }
+          }
+          throwAbandonIfNeeded(null);
         }
-        throwAbandonIfNeeded(null);
+      }
+      finally
+      {
+        entries.close();
       }
     }
     catch (SizeLimitExceededException slee)
@@ -886,10 +932,17 @@
               controller.getObjectSearchFilter(),
               ctls);
 
-    while (entries.hasMore())
+    try
     {
-      sr = entries.next();
-      sr.setName(dn);
+      while (entries.hasMore())
+      {
+        sr = entries.next();
+        sr.setName(dn);
+      }
+    }
+    finally
+    {
+      entries.close();
     }
     return sr;
   }
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/datamodel/CustomSearchResult.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/datamodel/CustomSearchResult.java
index 76e71fa..7b01be9 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/datamodel/CustomSearchResult.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/datamodel/CustomSearchResult.java
@@ -135,20 +135,27 @@
     if (attrs != null)
     {
       NamingEnumeration<?> en = attrs.getAll();
-      while (en.hasMore()) {
-        Attribute attr = (Attribute)en.next();
-        String attrName = attr.getID();
-        attrNames.add(attrName);
-        List<Object> values = new ArrayList<Object>();
-        for (int i=0; i<attr.size(); i++)
-        {
-          Object v = attr.get(i);
-          if (!"".equals(v.toString()))
+      try
+      {
+        while (en.hasMore()) {
+          Attribute attr = (Attribute)en.next();
+          String attrName = attr.getID();
+          attrNames.add(attrName);
+          List<Object> values = new ArrayList<Object>();
+          for (int i=0; i<attr.size(); i++)
           {
-            values.add(v);
+            Object v = attr.get(i);
+            if (!"".equals(v.toString()))
+            {
+              values.add(v);
+            }
           }
+          attributes.put(attrName.toLowerCase(), values);
         }
-        attributes.put(attrName.toLowerCase(), values);
+      }
+      finally
+      {
+        en.close();
       }
     }
     toString = calculateToString();
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/AddToGroupTask.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/AddToGroupTask.java
index 1c7f3ca..34afc81 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/AddToGroupTask.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/AddToGroupTask.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2008-2009 Sun Microsystems, Inc.
+ *      Copyright 2008-2010 Sun Microsystems, Inc.
  */
 
 package org.opends.guitools.controlpanel.task;
@@ -259,50 +259,57 @@
           Utilities.getJNDIName(groupDn.toString()),
           filter, ctls);
 
-    while (result.hasMore())
+    try
     {
-      SearchResult sr = result.next();
-      Set<String> values =
-        ConnectionUtils.getValues(sr, ServerConstants.ATTR_UNIQUE_MEMBER);
-      Set<String> dnsToAdd = new LinkedHashSet<String>();
-      if (values != null)
+      while (result.hasMore())
       {
-        for (DN newDn : dns)
+        SearchResult sr = result.next();
+        Set<String> values =
+          ConnectionUtils.getValues(sr, ServerConstants.ATTR_UNIQUE_MEMBER);
+        Set<String> dnsToAdd = new LinkedHashSet<String>();
+        if (values != null)
         {
-          boolean found = false;
-          for (String dn : values)
+          for (DN newDn : dns)
           {
-            if (Utilities.areDnsEqual(dn, newDn.toString()))
+            boolean found = false;
+            for (String dn : values)
             {
-              found = true;
-              break;
+              if (Utilities.areDnsEqual(dn, newDn.toString()))
+              {
+                found = true;
+                break;
+              }
+            }
+            if (!found)
+            {
+              dnsToAdd.add(newDn.toString());
             }
           }
-          if (!found)
+        }
+        else
+        {
+          for (DN newDn : dns)
           {
             dnsToAdd.add(newDn.toString());
           }
         }
-      }
-      else
-      {
-        for (DN newDn : dns)
+        if (dnsToAdd.size() > 0)
         {
-          dnsToAdd.add(newDn.toString());
+          Attribute attribute =
+            new BasicAttribute(ServerConstants.ATTR_UNIQUE_MEMBER);
+          for (String dn : dnsToAdd)
+          {
+            attribute.add(dn);
+          }
+          modifications.add(new ModificationItem(
+              DirContext.ADD_ATTRIBUTE,
+              attribute));
         }
       }
-      if (dnsToAdd.size() > 0)
-      {
-        Attribute attribute =
-          new BasicAttribute(ServerConstants.ATTR_UNIQUE_MEMBER);
-        for (String dn : dnsToAdd)
-        {
-          attribute.add(dn);
-        }
-        modifications.add(new ModificationItem(
-            DirContext.ADD_ATTRIBUTE,
-            attribute));
-      }
+    }
+    finally
+    {
+      result.close();
     }
     return modifications;
   }
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteEntryTask.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteEntryTask.java
index 6d4ac1f..d3541b8 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteEntryTask.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteEntryTask.java
@@ -367,17 +367,24 @@
         ctx.search(Utilities.getJNDIName(dnToRemove.toString()), filter, ctls);
 
       DN entryDNFound = dnToRemove;
-      while (entryDNs.hasMore())
+      try
       {
-        SearchResult sr = entryDNs.next();
-        if (!sr.getName().equals(""))
+        while (entryDNs.hasMore())
         {
-          CustomSearchResult res =
-            new CustomSearchResult(sr, dnToRemove.toString());
-          entryDNFound = DN.decode(res.getDN());
-          deleteSubtreeRecursively(ctx, entryDNFound, null, toNotify);
+          SearchResult sr = entryDNs.next();
+          if (!sr.getName().equals(""))
+          {
+            CustomSearchResult res =
+              new CustomSearchResult(sr, dnToRemove.toString());
+            entryDNFound = DN.decode(res.getDN());
+            deleteSubtreeRecursively(ctx, entryDNFound, null, toNotify);
+          }
         }
       }
+      finally
+      {
+        entryDNs.close();
+      }
 
     } catch (NameNotFoundException nnfe) {
       // The entry is not there: it has been removed
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteSchemaElementsTask.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteSchemaElementsTask.java
index 61f3ad0..a670029 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteSchemaElementsTask.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/DeleteSchemaElementsTask.java
@@ -649,20 +649,20 @@
     }
     boolean hasSuperior = false;
     Set<ObjectClass> newSuperiors = new LinkedHashSet<ObjectClass>();
-    for(ObjectClass sup : ocToDelete.getSuperiorClasses())
+    for (ObjectClass sup : ocToDelete.getSuperiorClasses())
     {
       boolean isFound = false;
-      for(ObjectClass oc: providedOcsToDelete)
+      for (ObjectClass oc: providedOcsToDelete)
       {
         if(sup.equals(oc))
         {
           hasSuperior = true;
           isFound = true;
-          newSuperiors.add(getNewSuperior(oc));
+          newSuperiors.addAll(getNewSuperiors(oc));
           break;
         }
       }
-      if(!isFound)
+      if (!isFound)
       {
         //Use the same super if not found in the list.
         newSuperiors.add(sup);
@@ -715,22 +715,29 @@
   }
 
 
-  private ObjectClass getNewSuperior(ObjectClass currentSup)
+  private Set<ObjectClass> getNewSuperiors(ObjectClass currentSup)
   {
-    if(currentSup.getSuperiorClasses() == null ||
-            currentSup.getSuperiorClasses().isEmpty())
-     {
-       return currentSup;
-     }
-
-     if(providedOcsToDelete.contains(currentSup))
-     {
-      for(ObjectClass o : currentSup.getSuperiorClasses())
+    Set<ObjectClass> newSuperiors = new LinkedHashSet<ObjectClass>();
+    if (currentSup.getSuperiorClasses() == null ||
+        currentSup.getSuperiorClasses().isEmpty())
+    {
+      // Nothing to do
+    }
+    else
+    {
+      for (ObjectClass o : currentSup.getSuperiorClasses())
       {
-       return getNewSuperior(o);
+        if (providedOcsToDelete.contains(o))
+        {
+          newSuperiors.addAll(getNewSuperiors(o));
+        }
+        else
+        {
+          newSuperiors.add(o);
+        }
       }
-     }
-     return null;
+    }
+    return newSuperiors;
   }
 
 
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
index bca2c3c..4b61f5f 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2008-2009 Sun Microsystems, Inc.
+ *      Copyright 2008-2010 Sun Microsystems, Inc.
  */
 
 package org.opends.guitools.controlpanel.task;
@@ -294,19 +294,26 @@
         NamingEnumeration<SearchResult> entries =
           ctx.search(Utilities.getJNDIName(dn.toString()), filter, ctls);
 
-        while (entries.hasMore())
+        try
         {
-          SearchResult sr = entries.next();
-          Set<String> dns = ConnectionUtils.getValues(sr, attrName);
-          for (String sDn : dns)
+          while (entries.hasMore())
           {
-            if (bindDN.equals(DN.decode(sDn)))
+            SearchResult sr = entries.next();
+            Set<String> dns = ConnectionUtils.getValues(sr, attrName);
+            for (String sDn : dns)
             {
-              isBoundAs = true;
-              break;
+              if (bindDN.equals(DN.decode(sDn)))
+              {
+                isBoundAs = true;
+                break;
+              }
             }
           }
         }
+        finally
+        {
+          entries.close();
+        }
       }
       catch (Throwable t)
       {
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
index 95ef96f..d6ed200 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
@@ -958,7 +958,15 @@
       NamingEnumeration<SearchResult> en =
         ctx.search("cn=Version,cn=monitor", "objectclass=*",
           searchControls);
-      SearchResult sr = en.next();
+      SearchResult sr = null;
+      try
+      {
+        sr = en.next();
+      }
+      finally
+      {
+        en.close();
+      }
       CustomSearchResult csr =
         new CustomSearchResult(sr, "cn=Version,cn=monitor");
 
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/ConfigFromDirContext.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/ConfigFromDirContext.java
index 35df024..789d655 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/ConfigFromDirContext.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/ConfigFromDirContext.java
@@ -826,10 +826,17 @@
       javaVersion = null;
       numberConnections = -1;
 
-      while (monitorEntries.hasMore())
+      try
       {
-        SearchResult sr = monitorEntries.next();
-        handleMonitoringSearchResult(sr, "cn=monitor");
+        while (monitorEntries.hasMore())
+        {
+          SearchResult sr = monitorEntries.next();
+          handleMonitoringSearchResult(sr, "cn=monitor");
+        }
+      }
+      finally
+      {
+        monitorEntries.close();
       }
     }
     catch (NamingException ne)
@@ -858,10 +865,17 @@
       NamingEnumeration<SearchResult> taskEntries =
         ctx.search(jndiName, filter, ctls);
 
-      while (taskEntries.hasMore())
+      try
       {
-        SearchResult sr = taskEntries.next();
-        handleTaskSearchResult(sr, ConfigConstants.DN_TASK_ROOT, ts);
+        while (taskEntries.hasMore())
+        {
+          SearchResult sr = taskEntries.next();
+          handleTaskSearchResult(sr, ConfigConstants.DN_TASK_ROOT, ts);
+        }
+      }
+      finally
+      {
+        taskEntries.close();
       }
     }
     catch (NamingException ne)
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/LDAPEntryReader.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/LDAPEntryReader.java
index db80d86..49837fe 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/LDAPEntryReader.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/LDAPEntryReader.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2008-2009 Sun Microsystems, Inc.
+ *      Copyright 2008-2010 Sun Microsystems, Inc.
  */
 
 package org.opends.guitools.controlpanel.util;
@@ -72,6 +72,7 @@
   public CustomSearchResult processBackgroundTask() throws Throwable
   {
     isOver = false;
+    NamingEnumeration<SearchResult> en = null;
     try
     {
       SearchControls controls = new SearchControls();
@@ -82,8 +83,7 @@
       controls.setSearchScope(SearchControls.OBJECT_SCOPE);
       final String filter = "(|(objectclass=*)(objectclass=ldapsubentry))";
 
-      NamingEnumeration<SearchResult> en =
-        ctx.search(Utilities.getJNDIName(dn), filter, controls);
+      en = ctx.search(Utilities.getJNDIName(dn), filter, controls);
 
       SearchResult sr = en.next();
 
@@ -95,6 +95,10 @@
       {
         isOver = true;
       }
+      if (en != null)
+      {
+        en.close();
+      }
     }
   }
 
diff --git a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/RemoteSchemaLoader.java b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/RemoteSchemaLoader.java
index 0711ca8..682b8c3 100644
--- a/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/RemoteSchemaLoader.java
+++ b/opendj-sdk/opends/src/guitools/org/opends/guitools/controlpanel/util/RemoteSchemaLoader.java
@@ -93,7 +93,15 @@
       ctx.search(ConfigConstants.DN_DEFAULT_SCHEMA_ROOT,
           filter,
           searchControls);
-    SearchResult sr = srs.next();
+    SearchResult sr = null;
+    try
+    {
+      sr = srs.next();
+    }
+    finally
+    {
+      srs.close();
+    }
     CustomSearchResult csr = new CustomSearchResult(sr,
         ConfigConstants.DN_DEFAULT_SCHEMA_ROOT);
 
diff --git a/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/installer/Installer.java b/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/installer/Installer.java
index b898478..e682883 100644
--- a/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/installer/Installer.java
+++ b/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/installer/Installer.java
@@ -4595,8 +4595,15 @@
       {
         NamingEnumeration<SearchResult> res =
           ctx.search(dn, filter, searchControls);
-        SearchResult sr = res.next();
-
+        SearchResult sr = null;
+        try
+        {
+          sr = res.next();
+        }
+        finally
+        {
+          res.close();
+        }
         // Get the number of entries that have been handled and
         // a percentage...
         Message msg;
@@ -4890,7 +4897,15 @@
       {
         NamingEnumeration<SearchResult> res =
           ctx.search(dn, filter, searchControls);
-        SearchResult sr = res.next();
+        SearchResult sr = null;
+        try
+        {
+          sr = res.next();
+        }
+        finally
+        {
+          res.close();
+        }
         String logMsg = getFirstValue(sr, "ds-task-log-message");
         if (logMsg != null)
         {
diff --git a/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/util/Utils.java b/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/util/Utils.java
index 5911286..bdc996f 100644
--- a/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/util/Utils.java
+++ b/opendj-sdk/opends/src/quicksetup/org/opends/quicksetup/util/Utils.java
@@ -1754,19 +1754,26 @@
       LdapName jndiName = new LdapName("cn=monitor");
       NamingEnumeration<?> listeners = ctx.search(jndiName, filter, ctls);
 
-      while (listeners.hasMore())
+      try
       {
-        SearchResult sr = (SearchResult)listeners.next();
+        while (listeners.hasMore())
+        {
+          SearchResult sr = (SearchResult)listeners.next();
 
-        v = getFirstValue(sr, "currentTime");
+          v = getFirstValue(sr, "currentTime");
 
-        TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
+          TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
 
-        SimpleDateFormat formatter =
-             new SimpleDateFormat("yyyyMMddHHmmss'Z'");
-        formatter.setTimeZone(utcTimeZone);
+          SimpleDateFormat formatter =
+            new SimpleDateFormat("yyyyMMddHHmmss'Z'");
+          formatter.setTimeZone(utcTimeZone);
 
-        time = formatter.parse(v).getTime();
+          time = formatter.parse(v).getTime();
+        }
+      }
+      finally
+      {
+        listeners.close();
       }
     }
     catch (Throwable t)
diff --git a/opendj-sdk/opends/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java b/opendj-sdk/opends/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java
index 9e35a95..dd7fc63 100644
--- a/opendj-sdk/opends/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java
+++ b/opendj-sdk/opends/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java
@@ -22,7 +22,7 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2008 Sun Microsystems, Inc.
+ *      Copyright 2008-2010 Sun Microsystems, Inc.
  */
 package org.opends.server.admin.client.ldap;
 
@@ -235,8 +235,15 @@
     try {
       NamingEnumeration<SearchResult> results = dirContext.search(dn, filter,
           controls);
-      if (results.hasMore()) {
-        return true;
+      try
+      {
+        if (results.hasMore()) {
+          return true;
+        }
+      }
+      finally
+      {
+        results.close();
       }
     } catch (NameNotFoundException e) {
       // Fall through - entry not found.
@@ -262,11 +269,18 @@
     List<LdapName> children = new LinkedList<LdapName>();
     NamingEnumeration<SearchResult> results = dirContext.search(dn, filter,
         controls);
-    while (results.hasMore()) {
-      SearchResult sr = results.next();
-      LdapName child = new LdapName(dn.getRdns());
-      child.add(new Rdn(sr.getName()));
-      children.add(child);
+    try
+    {
+      while (results.hasMore()) {
+        SearchResult sr = results.next();
+        LdapName child = new LdapName(dn.getRdns());
+        child.add(new Rdn(sr.getName()));
+        children.add(child);
+      }
+    }
+    finally
+    {
+      results.close();
     }
 
     return children;
diff --git a/opendj-sdk/opends/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java b/opendj-sdk/opends/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
index e111222..b6618a1 100644
--- a/opendj-sdk/opends/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
+++ b/opendj-sdk/opends/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
@@ -7745,7 +7745,15 @@
       {
         NamingEnumeration<SearchResult> res =
           ctx.search(dn, filter, searchControls);
-        SearchResult sr = res.next();
+        SearchResult sr = null;
+        try
+        {
+          sr = res.next();
+        }
+        finally
+        {
+          res.close();
+        }
         String logMsg = getFirstValue(sr, "ds-task-log-message");
         if (logMsg != null)
         {
@@ -7898,7 +7906,15 @@
       {
         NamingEnumeration<SearchResult> res =
           ctx.search(dn, filter, searchControls);
-        SearchResult sr = res.next();
+        SearchResult sr = null;
+        try
+        {
+          sr = res.next();
+        }
+        finally
+        {
+          res.close();
+        }
 
         // Get the number of entries that have been handled and
         // a percentage...

--
Gitblit v1.10.0