Manage Users in Java

The following example shows how to add, get, update, and delete a customer’s user with the following Customer Management service operations.

This example has been developed and run within the environment described in Getting Started Using Java with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.


// Command line usage:
// java ManageUsers
// 

import java.rmi.*;

import bingads.customermanagement.*;
import bingads.customermanagement.adapi.*;
import bingads.customermanagement.entities.*;
import bingads.customermanagement.exception.*;


/**
 *
 */
public class ManageUsers {

    private static String _namespace = null;
    private static BasicHttpBinding_ICustomerManagementServiceStub _service = null;

    // API credentials.

    private static String m_username = "<UserNameGoesHere>";
    private static String m_password = "<PasswordGoesHere>";
    private static String m_token = "<DeveloperTokenGoesHere>";
    
    // Specify the identifier of the customer for managing users

    private static long m_customerId = <CustomerIdGoesHere>; 
    
    /**
     */
    public static void main(String[] args) {
        CustomerManagementServiceLocator locator = null;
        
        try
        {
            locator = new CustomerManagementServiceLocator();
            _namespace = locator.getServiceName().getNamespaceURI();
            _service = (BasicHttpBinding_ICustomerManagementServiceStub) locator.getBasicHttpBinding_ICustomerManagementService();

            // Set the header properties.

            _service.clearHeaders();
            _service.setHeader(_namespace, "DeveloperToken", m_token);
            _service.setHeader(_namespace, "UserName", m_username);
            _service.setHeader(_namespace, "Password", m_password);

            // Create a new user data object and add it to specified customer
            System.out.printf("Adding new user within CustomerId %d.\n", m_customerId);
            User user = CreateUserData();
            user.setCustomerId(m_customerId);
            long userId = AddUser(user);

            // Get and print all active users managed by the specified customer
            System.out.printf("Printing all active users within CustomerId %d.\n", m_customerId);
            UserInfo[] infos = GetUsers(m_customerId);
            for (UserInfo info : infos)
            {
                user = GetUserData(info.getId());

                if (null == user)
                {
                    System.out.printf("Unable to access data for user %s (%d).\n", info.getUserName(), info.getId());
                }
                else
                {
                    // Filter out the users
                    // who have been deleted or are inactive.

                    if (user.getUserLifeCycleStatus() != UserLifeCycleStatus.Deleted &&
                        user.getUserLifeCycleStatus() != UserLifeCycleStatus.Inactive)
                        PrintUserData(user);
                }
            }

            // Ensure AddUser succeeded before updating and deleting the same user
            if (userId > 0)
            {
                // Update the user and print updated details
                UpdateUser(userId);
                user = GetUserData(userId);
                PrintUserData(user);

                // Delete the recently added and updated user
                DeleteUser(userId);
            }
        }
        catch (RemoteException e)
        {
            System.out.println("Service communication error encountered: ");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        catch (Exception e)
        {
            // Ignore fault exceptions that we already caught.

            if ( e.getCause() instanceof AdApiFaultDetail ||
                 e.getCause() instanceof ApiFault )
            {
                ;
            }
            else
            {
                System.out.println("Error encountered: ");
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    // Get the information of the user to add.

    static private User CreateUserData()
    {
        User user = new User();
        ContactInfo contact = new ContactInfo();
        Address address = new Address();
        PersonName name = new PersonName();

        address.setLine1("1234 Washington Place");
        address.setLine2("Suite 1210");
        address.setCity("Woodinville");
        address.setStateOrProvince("WA");
        address.setPostalCode("98068");
        address.setCountryCode("US");
        contact.setAddress(address);

        contact.setContactByPhone(true);
        contact.setPhone1("(206) 555-0100 ext. 1234");
        contact.setEmail("kim@alpineskihouse.com");
        contact.setEmailFormat(EmailFormat.Text);

        user.setContactInfo(contact);

        user.setCustomerAppScope(ApplicationType.Advertiser);

        name.setFirstName("Kim");
        name.setLastName("Abercrombie");
        user.setName(name);

        user.setPassword("<NewPasswordGoesHere>");
        user.setSecretQuestion(SecretQuestion.FatherMiddleName);
        user.setSecretAnswer("Michael");
        user.setUserName("kaberc");

        return user;
    }

    // Add a user to the specified customer.

    static private long AddUser(User user) throws RemoteException, Exception
    {
        AddUserRequest request = new AddUserRequest();
        AddUserResponse response = null;

        try
        {
            // If you do not specify Role, the default is the
            // AdvertiserCampaignManager user role. If you do
            // not specify a list of account identifiers, the user
            // will have AdvertiserCampaignManager permission to
            // all accounts that the customer manages.

            request.setUser(user);
            request.setAccountIds(null);
            request.setRole(UserRole.AdvertiserCampaignManager);

            response = _service.addUser(request);
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("AddUser failed with the following faults:\n");

            for (AdApiError error : fault.getErrors())
            {
                System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetail());
            }

            throw new Exception("", fault);
        }
        catch (ApiFault fault)
        {
            // Log this fault.

            System.out.println("AddUser failed with the following faults:\n");

            for (OperationError error : fault.getOperationErrors())
            {
                if (1339 == error.getCode())
                {
                    System.out.printf("A user with username %s already exists.", user.getUserName());
                }
                else
                {
                    System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetails());
                }
            }

            throw new Exception("", fault);
        }

        return (null != response) ? response.getId() : -1;
    }

    // Get a list of the users
    // who belong to the specified customer.

    static UserInfo[] GetUsers(long customerId) throws RemoteException, Exception
    {
        GetUsersInfoRequest request = new GetUsersInfoRequest();
        GetUsersInfoResponse response = null;
        
        try
        {
            request.setCustomerId(customerId);

            response = _service.getUsersInfo(request);
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("GetUsersInfo failed with the following faults:\n");

            for (AdApiError error : fault.getErrors())
            {
                System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetail());
            }

            throw new Exception("", fault);
        }
        catch (ApiFault fault)
        {
            // Log this fault.

            System.out.println("GetUsersInfo failed with the following faults:\n");

            for (OperationError error : fault.getOperationErrors())
            {
                System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetails());
            }

            throw new Exception("", fault);
        }

        return response.getUsersInfo();
    }


    // Gets the user data object

    static User GetUserData(long userId) throws RemoteException, Exception
    {
        GetUserRequest request = new GetUserRequest();
        GetUserResponse response = null;
        
        // Set the request information.

        request.setUserId(userId);

        try
        {
            response = _service.getUser(request);
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("GetUser failed with the following faults:\n");

            for (AdApiError error : fault.getErrors())
            {
                System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetail());
            }

            throw new Exception("", fault);
        }
        catch (ApiFault fault)
        {
            // Log this fault.

            System.out.println("GetUser failed with the following faults:\n");

            for (OperationError error : fault.getOperationErrors())
            {
                if (1001 == error.getCode())
                {
                    System.out.printf("You do not have permissions to access user %d.\n", userId);
                }
                else
                {
                    System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetails());
                }
            }

            throw new Exception("", fault);
        }

        return (null == response) ? null : response.getUser();
    }

    // Print some of the user data.

    private static void PrintUserData(User user)
    {
        System.out.println("Name: " + GetUserName(user.getName()));
        System.out.println("ID: " + user.getId());
        System.out.printf("Address: %s %s, %s %s", user.getContactInfo().getAddress().getLine1(),
            user.getContactInfo().getAddress().getCity(),
            user.getContactInfo().getAddress().getStateOrProvince(),
            user.getContactInfo().getAddress().getPostalCode());

        System.out.println("Contact by:");
        System.out.println("\tEmail at " + user.getContactInfo().getEmail());

        if (user.getContactInfo().getContactByPhone() != null)
        {
            System.out.println("\tPhone at " + user.getContactInfo().getPhone1());
        }
        if (user.getContactInfo().getContactByPostalMail() != null)
        {
            System.out.println("\tPostal mail sent to the above address ");
        }

        System.out.println("Logon user name: " + user.getUserName());
        System.out.println("Status: " + user.getUserLifeCycleStatus());
    }

    // Get the user's full name and return it as a String.

    private static String GetUserName(PersonName person)
    {
        String name = person.getFirstName();

        if (null != person.getMiddleInitial())
        {
            name += " " + person.getMiddleInitial() + ".";
        }

        name += " " + person.getLastName();

        return name;
    }

    // Update the user's data.
    // The update will fail if another user updated the user data
    // between the time that you retrieved the user object
    // and the time you that called the UpdateUser operation.

    static void UpdateUser(long userId) throws RemoteException, Exception
    {
        UpdateUserRequest request = new UpdateUserRequest();
        User user = GetUserData(userId);

        if (null != user)
        {
            // You can update all elements that are not marked as
            // read-only on MSDN. Update the fields as appropriate.
            // This example updates
            // the user's secret question and answer.

            user.setSecretQuestion(SecretQuestion.HighSchoolName);
            user.setSecretAnswer("Bainbridge HS");
            
            try
            {
                request.setUser(user);

                _service.updateUser(request);

                System.out.printf("User %s (%d) was successfully updated.\n", user.getUserName(), userId);
            }
            catch (AdApiFaultDetail fault)
            {
                // Log this fault.

                System.out.printf("The following errors occurred while updating user, %s (%d).\n", user.getUserName(), userId);

                for (AdApiError error : fault.getErrors())
                {
                    System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetail());
                }

                throw new Exception("", fault);
            }
            catch (ApiFault fault)
            {
                // Log this fault.

                System.out.printf("The following errors occurred while updating account, %s (%d).\n", user.getUserName(), userId);

                for (OperationError error : fault.getOperationErrors())
                {
                    if (1001 == error.getCode())
                    {
                        // You cannot update the read-only fields,
                        // such as the status fields.

                        System.out.println("You do not have permissions to update one or more of the fields.\n");
                    }
                    else if (510 == error.getCode())
                    {
                        // You should consider retrieving the user
                        // object again to get the new time stamp
                        // and data, show the latest updates to
                        // the user, and confirm that they want to
                        // continue with their update,
                        // update the elements as appropriate,
                        // and then call the UpdateUser operation.

                        System.out.println("Another user updated the user.\n");
                    }
                    else
                    {
                        System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetails());
                    }
                }

                throw new Exception("", fault);
            }
        }
    }

    // Delete the specified user.
    // The delete will fail if another user updates the user data
    // between the time that you retrieved the user object and the
    // time that you called the DeleteUser operation.

    static void DeleteUser(long userId) throws RemoteException, Exception
    {
        DeleteUserRequest request = new DeleteUserRequest();
        User user = GetUserData(userId);

        if (null != user)
        {
            try
            {
                // Set the request information.

                request.setUserId(userId);
                request.setTimeStamp(user.getTimeStamp());

                _service.deleteUser(request);

                System.out.printf("User %s (%d) was successfully deleted.\n", user.getUserName(), userId);
            }
            catch (AdApiFaultDetail fault)
            {
                // Log this fault.

                System.out.printf("The following errors occurred while deleting account, %s (%d).\n", user.getUserName(), userId);

                for (AdApiError error : fault.getErrors())
                {
                    System.out.printf("Error code: %d\nMessage: %s\nDetail: %s\n", error.getCode(), error.getMessage(), error.getDetail());
                }

                throw new Exception("", fault);
            }
            catch (ApiFault fault)
            {
                // Log this fault.

                System.out.printf("The following errors occurred while deleting account, %s (%d).\n", user.getUserName(), userId);

                for (OperationError error : fault.getOperationErrors())
                {
                    if (1001 == error.getCode())
                    {
                        System.out.printf("You do not have permissions to delete user, %s (%d).\n", user.getUserName(), userId);
                    }
                    else if (510 == error.getCode())
                    {
                        // You should consider retrieving the
                        // user object again to get the new
                        // time stamp and data, show the latest
                        // updates to the user, and confirm that
                        // they want to continue with their delete.
                        // If so, call DeleteUser with the new time stamp.

                        System.out.println("Another user updated the user before you could delete them.\n");
                    }
                    else if (1341 == error.getCode())
                    {
                        // You cannot delete a user who is the
                        // primary user of an account.
                        // Before you can delete users, you must
                        // remove them as the primary user of the
                        // accounts. See the PrimaryUserId element
                        // of the Account object.

                        System.out.println("You cannot delete the user because it is the primary user of one or more accounts.\n");
                    }
                    else
                    {
                        System.out.printf("Error code: %d\nMessage: %s\nDetails: %s\n", error.getCode(), error.getMessage(), error.getDetails());
                    }
                }

                throw new Exception("", fault);
            }
        }
    }
}



Community Additions

Show: