Manage Customers in Java

The following example shows how to get and update customers using 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 ManageCustomers
// 

import java.rmi.*;

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


/**
 *
 */
public class ManageCustomers {

    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>";
   
    
    /**
     */
    public static void main(String[] args) {
        CustomerManagementServiceLocator locator = null;
        long[] ids = 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);

            // To filter the list of customers for a specific
            // customer or set of customers whose names begin
            // with the same specific sequence of characters,
            // replace filter empty string with the customer’s 
            // name or sequence of characters.

            String filter = "";
            CustomerInfo[] cInfos = GetCustomers(""); 
            Customer customer = null;

            // Print a list of all customers managed and requested by the user
            System.out.println("Printing all Customers with filter: " + filter);
            for (CustomerInfo cInfo : cInfos)
            {
                customer = GetCustomerData((java.lang.Long)(cInfo.getId()));

                if (null == customer)
                {
                    System.out.printf("Unable to access data for customer %s (%d)\n", cInfo.getName(), cInfo.getId());
                }
                else
                {
                    PrintCustomerData(customer);
                }
            }

            // Select one customer identifier to demonstrate customer update
            long m_customerid = (long)(cInfos[0].getId());

            System.out.printf("Printing Customer with identifier %d.\n", m_customerid);
            PrintCustomerData(GetCustomerData(m_customerid));

            UpdateCustomer(m_customerid);

            System.out.printf("Printing Customer with identifier %d after update try.\n", m_customerid);
            PrintCustomerData(GetCustomerData(m_customerid));

        }
        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();
            }
        }
    }

    // Gets the advertising customers that the user
    // has access to and that match the filter criteria.

    static CustomerInfo[] GetCustomers(String filter) throws RemoteException, Exception
    {
        GetCustomersInfoRequest request = new GetCustomersInfoRequest();
        GetCustomersInfoResponse response = null;
        
        // Specify the filter criteria.
        // If you do not specify the application scope filter,
        // the list will contain both advertising and publishing
        // customers (if you have customers of both types).

        // If the nameFilter parameter is not an empty string,
        // the operation returns customers
        // whose name begins with the specified filter string.

        // You must specify the number of customers that
        // the operation returns. For example, to get the first 
        // 100 customers that match the filter, set TopN to 100.

        request.setApplicationScope(ApplicationType.Advertiser);
        request.setCustomerNameFilter(filter);
        request.setTopN(Integer.MAX_VALUE);

        try
        {
            response = _service.getCustomersInfo(request);
            
            if (null == response.getCustomersInfo())
            {
                System.out.println("There are no customers that match the specified filter criteria.");
            }
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("GetCustomersInfo 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("GetCustomersInfo 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.getCustomersInfo();
    }


    // Get the customer data associated with
    // the specified customer identifier.

    static Customer GetCustomerData(long customerId) throws RemoteException, Exception
    {
        GetCustomerRequest request = new GetCustomerRequest();
        GetCustomerResponse response = null;
        
        // Set the request information.

        request.setCustomerId(customerId);

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

            System.out.println("GetCustomer 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("GetCustomer 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 (null == response) ? null : response.getCustomer();
    }

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

    static void UpdateCustomer(long customerId) throws RemoteException, Exception
    {
        UpdateCustomerRequest request = new UpdateCustomerRequest();
        Customer customer = GetCustomerData(customerId);

        if (null != customer)
        {
            // You can update all elements
            // that are not marked as read-only on MSDN.
            // Update the fields as appropriate.
            // This example updates the customer’s address.

            customer.getCustomerAddress().setLine1("6789 Rollingstone");
            customer.getCustomerAddress().setCity("Redmond");
            customer.getCustomerAddress().setPostalCode("98444");
            

            try
            {
                request.setCustomer(customer);

                _service.updateCustomer(request);

                System.out.printf("Customer %s (%d) was successfully updated.\n", customer.getName(), customerId);
            }
            catch (AdApiFaultDetail fault)
            {
                // Log this fault.

                System.out.printf("The following errors occurred while updating customer, %s (%d).\n", customer.getName(), customerId);

                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 customer, %s (%d).\n", customer.getName(), customerId);

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

                    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 customer object again to get 
                        // the new time stamp and data.
                        // You can then show the latest
                        // updates to the user and confirm
                        // that they want to continue with
                        // their update. If so, update the
                        // elements as appropriate, and call
                        // the UpdateCustomer operation.

                        System.out.println("Another user updated the customer.\n");
                    }
                    else
                    {
                        System.out.printf("The following error occurred trying to update customer %d.\n", customerId);
                        System.out.printf("Error code: %d\nMessage: %s\nDetails: %s\n", error.getCode(), error.getMessage(), error.getDetails());
                    }
                }

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

    // Print the contents of the Customer object.

    static void PrintCustomerData(Customer customer) throws RemoteException, Exception
    {
        System.out.printf("Customer: %s (%d)\n", customer.getName(), customer.getId());
        System.out.printf("Address: %s %s, %s %s\n", customer.getCustomerAddress().getLine1(),
                customer.getCustomerAddress().getCity(),
                customer.getCustomerAddress().getStateOrProvince(),
                customer.getCustomerAddress().getPostalCode());
        System.out.println("Status: " + customer.getCustomerLifeCycleStatus());
        System.out.println("Financial status: " + customer.getCustomerFinancialStatus());
        System.out.println("Service level: " + customer.getServiceLevel());
        System.out.println("Industry: " + customer.getIndustry());
        System.out.println("MarketCountry: " + customer.getMarketCountry());
        System.out.println("MarketLanguage: " + customer.getMarketLanguage());
        System.out.println("Last modified by: " + customer.getLastModifiedByUserId());
        System.out.println("\n\n"); 
    }
}



Community Additions

Show: