Export (0) Print
Expand All

Manage Accounts in Java

The following example shows how to get, update, and delete a customer’s account 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 ManageAccounts
// 

import java.rmi.*;

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


/**
 *
 */
public class ManageAccounts {

    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
    // whose accounts you want to get.

    private static long m_customerId = <CustomerIdGoesHere>; 
        
    /**
     */
    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);

            AccountInfo[] infos = GetAccounts(m_customerId);
            Account account;

            // Print a list of all accounts managed by the customer
            System.out.println("Printing all accounts managed by the customer.");
            for (AccountInfo info : infos)
            {
                account = GetAccountData(info.getId());

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

            // Select one account identifier to demonstrate account update and delete
            long accountId = infos[0].getId();

            System.out.printf("Printing Account with identifier %d.\n", accountId);
            PrintAccountData(GetAccountData(accountId));
                
            UpdateAccount(accountId);

            System.out.printf("Printing Account with identifier %d after update try.\n", accountId);
            PrintAccountData(GetAccountData(accountId));

            DeleteAccount(accountId);

            System.out.printf("Printing Account with identifier %d after delete try.\n", accountId);
            PrintAccountData(GetAccountData(accountId));
        }
        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 accounts info that the customer owns and manages

    static AccountInfo[] GetAccounts(long customerId) throws RemoteException, Exception
    {
        GetAccountsInfoRequest request = new GetAccountsInfoRequest();
        GetAccountsInfoResponse response = null;
        
        try
        {
            request.setCustomerId(customerId);
            response = _service.getAccountsInfo(request);
            
            if (null == response.getAccountsInfo())
            {
                System.out.println("The customer does not have any accounts.");
            }
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

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


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

    static Account GetAccountData(long accountId) throws RemoteException, Exception
    {
        GetAccountRequest request = new GetAccountRequest();
        GetAccountResponse response = null;
        
        try
        {
            request.setAccountId(accountId);

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

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

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

    static void UpdateAccount(long accountId) throws RemoteException, Exception
    {
        UpdateAccountRequest request = new UpdateAccountRequest();
        Account account = GetAccountData(accountId);

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

            String originalName = account.getName();
            account.setName(account.getName() + "_UPDATED");
            
            try
            {
                request.setAccount(account);

                // You cannot update or delete an account
                // that has been deleted.

                if (AccountLifeCycleStatus.Inactive != account.getAccountLifeCycleStatus())
                {
                    _service.updateAccount(request);

                    System.out.printf("Account %s (%d) was successfully updated.\n", account.getName(), accountId);
                }
                else
                {
                    System.out.printf("Account %s (%d) is Inactive and may not be updated.\n", originalName, accountId);
                }
            }
            catch (AdApiFaultDetail fault)
            {
                // Log this fault.

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

                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", originalName, accountId);

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

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

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

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

    static void DeleteAccount(long accountId) throws RemoteException, Exception
    {
        DeleteAccountRequest request = new DeleteAccountRequest();
        Account account = GetAccountData(accountId);

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

                request.setAccountId(accountId);
                request.setTimeStamp(account.getTimeStamp());

                _service.deleteAccount(request);

                System.out.printf("Account %s (%d) was successfully deleted.\n", account.getName(), accountId);
            }
            catch (AdApiFaultDetail fault)
            {
                // Log this fault.

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

                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", account.getName(), accountId);

                for (OperationError error : fault.getOperationErrors())
                {
                    if (1001 == error.getCode())
                    {
                        System.out.printf("You do not have permissions to delete account, %s (%d).\n", account.getName(), accountId);
                    }
                    else if (112 == error.getCode())
                    {
                        // Because the get operations will return
                        // accounts that have been deleted,
                        // you may want to confirm the account's
                        // status before trying to delete
                        // the account to avoid this error.

                        System.out.printf("Account %s (%d) has already been deleted.\n", account.getName(), accountId);
                    }
                    else if (510 == error.getCode())
                    {
                        // You should consider retrieving the
                        // account 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 the DeleteAccount
                        // operation with the new time stamp.

                        System.out.printf("Another user updated account %s (%d) before you could delete it.\n", account.getName(), accountId);
                    }
                    else
                    {
                        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 Account object.

    static void PrintAccountData(Account account) throws RemoteException, Exception
    {
        System.out.println("BillToCustomerId: " + account.getBillToCustomerId());
        System.out.println("CountryCode: " + account.getCountryCode());
        System.out.println("CurrencyType: " + account.getCurrencyType());
        System.out.println("FinancialStatus: " + account.getAccountFinancialStatus());
        System.out.println("ID: " + account.getId());
        System.out.println("Language: " + account.getLanguage());
        System.out.println("Name: " + account.getName());
        System.out.println("Number: " + account.getNumber());
        System.out.println("ParentCustomerId: " + account.getParentCustomerId());
        System.out.println("PaymentMethodId: " + account.getPaymentMethodId());
        System.out.println("PrimaryUserId: " + account.getPrimaryUserId());
        System.out.println("Status: " + account.getAccountLifeCycleStatus());
        System.out.println("Last modified by: " + account.getLastModifiedByUserId());

        if (AccountType.Advertiser == account.getAccountType())
        {
            System.out.println("AgencyContactName: " + ((AdvertiserAccount) account).getAgencyContactName());
            System.out.println("AgencyCustomerId: " + ((AdvertiserAccount) account).getAgencyCustomerId());
            System.out.println("SalesHouseCustomerId: " + ((AdvertiserAccount) account).getSalesHouseCustomerId());
        }

        System.out.println("\n"); 
    }
}



Community Additions

Show:
© 2014 Microsoft