/* **************************************************************************

  $Archive: /njcl_v2rmi/src/com/novell/service/nw/SLPNamesEnumerator.java $
  $Revision: 9 $
  $Modtime: 12/07/00 2:40p $
 
  Copyright (c) 1998 Novell, Inc.  All Rights Reserved.

  THIS WORK IS  SUBJECT  TO  U.S.  AND  INTERNATIONAL  COPYRIGHT  LAWS  AND
  TREATIES.   NO  PART  OF  THIS  WORK MAY BE  USED,  PRACTICED,  PERFORMED
  COPIED, DISTRIBUTED, REVISED, MODIFIED, TRANSLATED,  ABRIDGED, CONDENSED,
  EXPANDED,  COLLECTED,  COMPILED,  LINKED,  RECAST, TRANSFORMED OR ADAPTED
  WITHOUT THE PRIOR WRITTEN CONSENT OF NOVELL, INC. ANY USE OR EXPLOITATION
  OF THIS WORK WITHOUT AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO
  CRIMINAL AND CIVIL LIABILITY.

****************************************************************************/
package com.novell.service.nw;

import java.util.*;
import com.novell.java.lang.IntegerBuffer;
import com.novell.service.jncp.*;
import com.novell.service.session.*;
import com.novell.service.session.xplat.CallsService;
import com.novell.service.session.xplat.Xplat;

/**
*  Enumerates all NetWare Trees or Server names available.
*/
class SLPNamesEnumerator implements Enumeration
{
   public static final int NO_MORE_ENTRIES = 0x8866;

   private CallsService service;
   private boolean more;
   private IntegerBuffer handle = new IntegerBuffer();
   private IntegerBuffer bufLen = new IntegerBuffer(512);
   private StringBuffer buf = new StringBuffer();
   private String name, oldName;
   private boolean open;

   public SLPNamesEnumerator(int objType, Hashtable hash)
   {
      try
      {
         Session s = (Session)hash.get(com.novell.utility.naming.Environment.SESSION_OBJECT);
         service = (CallsService)s.getService(CallsService.KEY);
         service.getObjectNamesBeginA(objType, handle);
         more = true;
         nextElement();
         open = true;
      }
      catch(Exception e)
      {
         throw NSIExceptionBuilder.build(e);
      }
   }

   protected void finalize() throws Throwable
   {
      close();
   }

   public void close()
   {
      if(open)
      {
         try
         {
            service.getObjectNamesEndA(handle);
            open = false;
         }
         catch(java.rmi.RemoteException e)
         {
            throw NSIExceptionBuilder.build(e);
         }
      }
   }

   public boolean hasMoreElements()
   {
      return more;
   }

   public Object nextElement()
   {
      if(!more)
         throw new NoSuchElementException();
      oldName = name;
      try
      {
         service.getObjectNamesNextA(handle, bufLen, buf);
         name = buf.toString();
      }
      catch(NSIException ne)
      {
         more = false;
         if(ne.getCCode() != NO_MORE_ENTRIES)
            throw ne;
      }
      catch(java.rmi.RemoteException e)
      {
         more = false;
         throw NSIExceptionBuilder.build(e);
      }
      return oldName;
   }
}
