Export (0) Print
Expand All

Search Customers by User in Java

The following example shows how to search for customers that can be managed by the current authenticated user.

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

To download the Bing Ads JARs imported in the sample, see Java Production JARs for Bing Ads API Version 9.

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.

import java.rmi.*;

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


/**
 *
 */
public class SearchByUser {

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

    // Specify API credentials.
     
    private static java.lang.String UserName = "<UserNameGoesHere>";
    private static java.lang.String Password = "<PasswordGoesHere>";
    private static java.lang.String DeveloperToken = "<DeveloperTokenGoesHere>";

    
    /**
     */
    public static void main(java.lang.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", DeveloperToken);
            _service.setHeader(_namespace, "UserName", UserName);
            _service.setHeader(_namespace, "Password", Password);
 
            // Get the User object for the current authenticated user, by calling GetUser
            // with a null UserId.
            // Later in this sample we will search for all customers and accounts
            // that the user may access.

            User user = GetUser(null);

            PrintUser(user);

            // Specify the page index and number of customer results per page.

            Paging pageInfo = new Paging();
            pageInfo.setIndex(0);   // The first page
            pageInfo.setSize(100);  // The first 100 customers for this page of results

            // Optionally specify the date range when the requested customers were created.
            // Min and Max are both optional, and you may specify one, both, or neither.

            DateRange dateRange = new DateRange();
            dateRange.setMaxDate("");
            dateRange.setMinDate("");

            // Specify whether the returned Customer list should be sorted by customer
            // name, number, or identifier.
            // You should only specify one OrderBy element in the array. 
            // Additional array items, if specified will be ignored by the service.

            OrderBy ordering = new OrderBy();
            ordering.setField(OrderByField.Number);
            ordering.setOrder(SortOrder.Ascending);

            // Given the user credentials authenticated above, search for customers by UserName.

            Predicate predicate = new Predicate();
            predicate.setField("UserName");
            predicate.setOperator(PredicateOperator.Equals);
            predicate.setValue(user.getUserName());

            // Search for customers that match the specified criteria.

            Customer[] customers = SearchCustomers(
                    dateRange,
                    new OrderBy[] { ordering },
                    pageInfo,
                    new Predicate[] { predicate });

            System.out.printf("Customer search results by UserName (%s):\n", user.getUserName());
            PrintCustomers(customers);
        }
        // Customer Management service operations can throw AdApiFaultDetail.
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

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

            // If the AdApiError array is not null, the following are examples of error codes that may be found.
	    for (AdApiError error : fault.getErrors())
            {
                System.out.printf("AdApiError\n");
                System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", error.getCode(), error.getErrorCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 105:   // InvalidCredentials
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }
        }
        // Customer Management service operations can throw ApiFault.
        catch (ApiFault fault)
        {
            // Log this fault.

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

            // If the OperationError array is not null, the following are examples of error codes that may be found.
            for (OperationError error : fault.getOperationErrors())
            {
                System.out.printf("OperationError\n");
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 106:   // UserIsNotAuthorized
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }
        }
        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 a User object by the specified UserId.

    static User GetUser(java.lang.Long userId) throws RemoteException, Exception
    {
        GetUserRequest request = new GetUserRequest();
        
        request.setUserId(userId);

        return _service.getUser(request).getUser();
    }


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

    static Customer[] SearchCustomers(
            DateRange dateRange,
            OrderBy[] ordering,
            Paging pageInfo,
            Predicate[] predicates) throws RemoteException, Exception
    {
        SearchCustomersRequest request = new SearchCustomersRequest();
        request.setApplicationScope(ApplicationType.Advertiser);
        request.setDateRange(dateRange);
        request.setOrdering(ordering);
        request.setPageInfo(pageInfo);
        request.setPredicates(predicates);

        return _service.searchCustomers(request).getCustomers();
    }


    // Returns a list of accounts such that the returned accounts
    // are within the specified customer identifier, and not managed
    // through an agency or reseller.

    static AccountInfo[] GetAccountsInfo(long customerId) throws RemoteException, Exception
    {
        GetAccountsInfoRequest request = new GetAccountsInfoRequest();
        
        request.setOnlyParentAccounts(true);
        request.setCustomerId(customerId);

        return _service.getAccountsInfo(request).getAccountsInfo();
    }


    // Prints the details of the specified user.

    static void PrintUser(User user)
    {
        if (user == null)
        {
            return;
        }

        if (user.getIsMigratedToMicrosoftAccount())
        {
            System.out.printf("The user is migrated to a Microsoft account, " +
                              "and the UserName field is the corresponding email address.\n\n");
        }
        else
        {
            System.out.printf("The user is not yet migrated to a Microsoft account, " +
                              "and the value of UserName is a legacy Bing Ads managed user.\n\n");
        }

        System.out.printf("UserName is %s\n", user.getUserName());
        System.out.printf("Bing Ads Email is %s\n", user.getContactInfo().getEmail());
        System.out.printf("User Id is %d\n", user.getId());
        System.out.printf("FirstName is %s\n", user.getName().getFirstName());
        if (user.getName().getMiddleInitial() != null)
        {
            System.out.printf("MiddleInitial is %s\n", user.getName().getMiddleInitial());
        }
        System.out.printf("LastName is %s\n\n", user.getName().getLastName());
    }

    // Prints a list of customers.

    static void PrintCustomers(Customer[] customers) throws RemoteException, Exception
    {
        for (Customer cust : customers)
        {
            if (cust.getId() != null)
            {
                System.out.printf("CustomerId: %d\n", cust.getId());

                AccountInfo[] aInfos = GetAccountsInfo((long)cust.getId());

                // Print a list of all accounts managed by the customer
                for (AccountInfo aInfo : aInfos)
                {
                    if (null != aInfo)
                    {
                        System.out.printf("CustomerAccountId: %d\n", aInfo.getId());
                    }
                }
            }

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

Community Additions

ADD
Show:
© 2014 Microsoft