/* $Novell: GetEffectivePrivileges.java,v 1.17 2003/08/21 11:51:41 $
 *
 * Copyright (C) 1999, 2000, 2001 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. 
 ***************************************************************************/
 
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPExtendedOperation;
import com.novell.ldap.LDAPExtendedResponse;
import com.novell.ldap.LDAPDSConstants;
import com.novell.ldap.extensions.GetEffectivePrivilegesListRequest;
import com.novell.ldap.extensions.GetEffectivePrivilegesListResponse;
import java.io.UnsupportedEncodingException;

/**
 *  The following sample demonstrates how get the rights that
 *  a trustee object has on the object for a string of attributes.
 *
 */

public class GetEffectivePrivilegesList implements LDAPDSConstants 
{
	public static void main( String[] args ) 
	{
		if (args.length != 6) 
		{
			System.err.println("Usage:   java GetEffectivePrivileges "
                            + "<host Name> <port number> <login dn> "
                            + "\n         <password> <object dn> <trustee dn>");
			System.err.println("Example: GetEffectivePrivileges Acme.com 389 "
                            + "\"cn=Admin,o=Acme\" secret\n         "
                            + "\"cn=james,o=Acme\" "
                            + "\"cn=admin,o=Acme\"");
			System.exit(1);
		}
		int    ldapVersion = LDAPConnection.LDAP_V3;
		String ldapHost    = args[0];
		int    ldapPort    = Integer.parseInt(args[1]);
		String loginDN     = args[2];
		String password    = args[3];
		String objectDN    = args[4];
		String trusteeDN   = args[5];
		int[]    iRight      = {0};
		String[] sRight      = null;
		LDAPConnection ld  = new LDAPConnection();
		try 
		{
			// connect to the server
			ld.connect( ldapHost, ldapPort);
			// bind to the server
			ld.bind( ldapVersion, loginDN, password.getBytes("UTF8") );
			System.out.println( "\nLogin succeeded");
			// user can choose from:
			//   1. object rights(represented as [Entry Rights]);
			//   2. attribute rights(represented as [All Attributes Rights];
			//   3. a single attribute name like 'acl'
			//String rightName = "{[Entry Rights],null}"
			//String rightName = "{[All Attributes Rights],null}";
			//String rightName = "{attr1,attr2,attr3,.... ,null}"
        	String[] rightName = {"acl","sn","dn",null};
			LDAPExtendedOperation request = new GetEffectivePrivilegesListRequest(objectDN,trusteeDN,rightName);
			LDAPExtendedResponse response = ld.extendedOperation(request); 
            
			if ( response.getResultCode() == LDAPException.SUCCESS && 
            		( response instanceof GetEffectivePrivilegesListResponse )) 
			{
				iRight = ((GetEffectivePrivilegesListResponse)response).getPrivileges();
				if(iRight.length == (rightName.length-1))
				{
					sRight = new String[iRight.length];
					for ( int i =0 ; rightName[i] != null ; i++)
					{
						if ( rightName[i].equalsIgnoreCase("[Entry Rights]") )
							sRight[i] = "object rights";
						else if ( rightName[i].equalsIgnoreCase("[All Attributes Rights]"))
							sRight[i] = "attribute rights";
						else
							sRight[i] = rightName[i];
					}
					System.out.println("\"" + trusteeDN + "\" has the following rights on \""+ objectDN+"\'s ");
					for(int i=0;rightName[i]!=null;i++)
					{
						System.out.println("'" + sRight[i] + "':");
						PrintRights( rightName[i], iRight[i] );
						System.out.println("\nGet Effective Privileges succeeded");
					}
				}
				else
				{
					System.out.println("You have provided the wrong input in terms of attribute list ");
				}
			}                   
			else 
			{                
				System.out.println("Get Effective Privileges Failed");
					throw new LDAPException( response.getErrorMessage(),response.getResultCode(),(String)null);
			}
            
			/* Done, so disconnect */
			if ( ld.isConnected() )
				ld.disconnect();
		}
		catch( LDAPException e ) {
			System.out.println( "Error: " + e.toString() );
		}
		catch( UnsupportedEncodingException e ) {
			System.out.println( "Error: " + e.toString() );
		}
	}
	// PrintRights() parses and prints the effective rights one by one
		public static void PrintRights( String aName, int rights )
    {
		StringBuffer rString = new StringBuffer();
		if ( aName.equalsIgnoreCase("[Entry Rights]")) {
			// decode object rights
			rString.append((rights & LDAP_DS_ENTRY_BROWSE) != 0 ? "BrowseEntry: true; ":"BrowseEntry: false; ");
			rString.append((rights & LDAP_DS_ENTRY_ADD) != 0 ? "AddEntry: true; ":"AddEntry: false; ");
			rString.append((rights & LDAP_DS_ENTRY_DELETE) != 0 ? "DeleteEntry: true; ":"DeleteEntry: false; ");
			rString.append((rights & LDAP_DS_ENTRY_RENAME) != 0 ? "RenameEntry: true; ":"RenameEntry: false; ");
			rString.append((rights & LDAP_DS_ENTRY_SUPERVISOR) != 0 ? "Supervisor: true; ":"Supervisor: false; ");
			rString.append((rights & LDAP_DS_ENTRY_INHERIT_CTL) != 0 ? "Inherit_ctl: true.":"Inherit_ctl: false.");
		}
		else {
				// decode attribute rights no matter it's for 
				// all attributes or a single attribute
				rString.append((rights & LDAP_DS_ATTR_COMPARE) != 0 ? "CompareAttributes: true; ": "CompareAttributes: false; ");
				rString.append((rights & LDAP_DS_ATTR_READ) != 0 ? "ReadAttributes: true; ":"ReadAttributes: false; ");
				rString.append((rights & LDAP_DS_ATTR_WRITE) != 0 ? "Write/Add/DeleteAttributes: true; ":"Write/Add/DeleteAttributes: false; ");
				rString.append((rights & LDAP_DS_ATTR_SELF) != 0 ? "Add/DeleteSelf: true; ":"Add/DeleteSelf: false; ");
				rString.append((rights & LDAP_DS_ATTR_SUPERVISOR) != 0 ? "Supervisor: true.":"Supervisor: false.");            
			}         
			System.out.println(rString);
	}
}
