//   Name:  CustomCreateExampleTask.java
//
//   Copyright (c) 1997-2004 Novell, Inc.  All Rights Reserved.
//
//   THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND TREATIES.
//   USE AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO THE LICENSE AGREEMENT
//   ACCOMPANYING THE SOFTWARE DEVELOPMENT KIT (SDK) THAT CONTAINS THIS WORK.
//   PURSUANT TO THE SDK LICENSE AGREEMENT, NOVELL HEREBY GRANTS TO DEVELOPER A
//   ROYALTY-FREE, NON-EXCLUSIVE LICENSE TO INCLUDE NOVELL'S SAMPLE CODE IN ITS
//   PRODUCT. NOVELL GRANTS DEVELOPER WORLDWIDE DISTRIBUTION RIGHTS TO MARKET,
//   DISTRIBUTE, OR SELL NOVELL'S SAMPLE CODE AS A COMPONENT OF DEVELOPER'S
//   PRODUCTS. NOVELL SHALL HAVE NO OBLIGATIONS TO DEVELOPER OR DEVELOPER'S
//   CUSTOMERS WITH RESPECT TO THIS CODE.

package com.company.plugins;

import com.novell.emframe.dev.*;
import com.novell.emframe.dev.D;

import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.LdapContext;
import java.util.Properties;

public class CustomCreateExampleTask extends eDirAccessService
{
   /**
    * Override this method to do java work after EDAS creates the object
    */
   protected boolean postCreate(TaskContext context, String username)
   {
      D.log("CustomCreateExampleTask: In postCreate");
      return true;
   }

   /**
    * Override this method to do java work before EDAS creates the object
    */
   protected boolean preCreate(String username, TaskContext context)
   {
      D.log("CustomCreateExampleTask: In preCreate");

      try
      {
         LdapContext lctx = (LdapContext) context.getAuthenticationBroker().getAPIObject("JndiLdap", null);

         SearchControls sc = new SearchControls(SearchControls.SUBTREE_SCOPE, 0, // count limit
                 0, // time limit
                 null, // string[] of attrs to return
                 false, // return obj
                 false); // dereference

         String filter = "(CN="+username+")";
         NamingEnumeration ne = lctx.search("", filter, sc);

         if(ne!=null&&ne.hasMore())
         {
            eMFrameUtils.setMessage("error", "Invalid Name", "There is already an object in the tree with this name.  Please choose another name.", context);
            return false;
         }
      }
      catch(Throwable e)
      {
         eMFrameUtils.setErrorMessage(e, context);
         return false;
      }

      return true;
   }
}
