Export (0) Print
Expand All

Get User Locations in Java

The following example shows how to get the geographical location of users who have searched for specific keywords using the Ad Intelligence GetKeywordLocations service operation.

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 GetLocations
//

import java.rmi.*;
import bingads.adintelligence.*;
import bingads.adintelligence.adapi.*;
import bingads.adintelligence.datacontracts.*;

/**
 *
 */
public class GetLocations {

    private static String namespace = null;
    private static BasicHttpBinding_IAdIntelligenceServiceStub service = null;

    // Specify your credentials.

    private static String m_password = "<passwordgoeshere>";
    private static String m_username = "<usernamegoeshere>";
    private static String m_token = "<devtokengoeshere>";

    // Specify the advertiser's account ID.

    private static long m_accountId = <accountidgoeshere>;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        AdIntelligenceServiceLocator locator = null;
        KeywordLocationResult[] locations = null;

        try
        {
            locator = new AdIntelligenceServiceLocator();
            namespace = locator.getServiceName().getNamespaceURI();
            service = (BasicHttpBinding_IAdIntelligenceServiceStub) locator.getBasicHttpBinding_IAdIntelligenceService();

            locations = GetLocations(m_accountId);

            if (locations != null)
            {
                for (KeywordLocationResult keyword : locations)
                {
                    System.out.println(keyword.getKeyword());

                    if (null == keyword.getDevice())
                    {
                        System.out.println("  There is no location data available for the keyword.\n");
                    }
                    else
                    {
                        System.out.println("  " + keyword.getDevice());

                        for (KeywordLocation location : keyword.getKeywordLocations())
                        {
                            System.out.printf("    %s (%.2f%%)\n", 
                                    location.getLocation(), 
                                    location.getPercentage());
                        }

                        System.out.println();
                    }
                }
            }
        }
        catch (RemoteException e)
        {
            if (new AdApiFaultDetail().getClass() == e.getClass() ||
                new ApiFaultDetail().getClass() == e.getClass())
            {
                ; // Ignore because we already caught these below.
            }
            else
            {
                System.out.print("Service communication error encountered: ");
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        catch (Exception e)
        {
            System.out.print("Error encountered: ");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Get the geographical location of users who have searched for the specified keywords.
     * The location information is broken out by device type.
     */

    public static KeywordLocationResult[] GetLocations(long accountId) throws RemoteException
    {
        GetKeywordLocationsRequest request = new GetKeywordLocationsRequest();
        GetKeywordLocationsResponse response = null;

        // Set the header properties.

        service.clearHeaders();
        service.setHeader(namespace, "DeveloperToken", m_token);
        service.setHeader(namespace, "UserName", m_username);
        service.setHeader(namespace, "Password", m_password);
        service.setHeader(namespace, "CustomerAccountId", m_accountId);

        // Specify request information.

        request.setKeywords(new String[] { "flower delivery" });
        request.setDevice(new String[] { "Smartphones", "Computers", "NonSmartphones" });
        request.setLanguage("English");
        request.setPublisherCountry("US");
        request.setLevel(2);  // By Metropolitan area
        request.setMaxLocations(5);
        request.setParentCountry("GB");  // Searches on Bing.com that originated in the United Kingdom.

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

            System.out.println("getKeywordLocations failed with the following faults:");

            for (AdApiError error : fault.getErrors())
            {
                if (105 == error.getCode()) //  InvalidCredentials
                {
                    System.out.println("The specified credentials are not valid or the account is inactive.");
                }
                else
                {
                    System.out.print("\tError code: " + error.getErrorCode());
                    System.out.println(" (" + error.getCode() + ")");
                    System.out.println("\tMessage: " + error.getMessage());
                    System.out.println("\tDetail: " + error.getDetail());
                }
            }

            throw fault;  // To be caught and ignored in main.
        }
        catch (ApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("getKeywordLocations failed with the following faults:");

            for (OperationError error : fault.getOperationErrors())
            {
                switch (error.getCode())
                {
                    case 106: //  UserIsNotAuthorized
                        System.out.println("The user is not authorized to call this operation.");
                        break;

                    case 1257: // CampaignServiceMissingLanguage
                        System.out.println("The language cannot be null or empty.");
                        break;

                    case 1505: // CampaignServiceKeywordsArrayShouldNotBeNullOrEmpty
                        System.out.println("The list of keywords cannot be null or empty.");
                        break;

                    case 3408: // CampaignServiceLanguageAndCountryNotSupported
                        System.out.println("One or more of the specified publisher countries is not allowed for the specified language.");
                        break;

                    case 3412: // CampaignServiceInvalidLanguage
                        System.out.println("The specified language is not valid.");
                        break;

                    case 3413: // CampaignServiceInvalidPublisherCountry
                        System.out.println("One or more of the specified publisher countries is not valid.");
                        break;

                    case 3414: // CampaignServiceInvalidLevel
                        System.out.println("The specified location is not valid.");
                        break;

                    case 3415: // CampaignServiceInvalidParentCountry
                        System.out.println("The specified user country is not valid.");
                        break;

                    case 3417: //CampaignServiceInvalidDevice
                        System.out.println("One or more of the specified devices is not a valid device type.");
                        break;

                    case 3418: //CampaignServiceInvalidMaxLocations
                        System.out.println("The specified number of locations to return is greater than the maximum allowed.");
                        break;

                    default:
                        System.out.print("\tError code: " + error.getErrorCode());
                        System.out.println(" (" + error.getCode() + ")");
                        System.out.println("\tMessage: " + error.getMessage());
                        System.out.println("\tDetail: " + error.getDetails());
                        break;
                }
            }

            for (BatchError error : fault.getBatchErrors())
            {
                System.out.print("\tError code: " + error.getErrorCode());
                System.out.println(" (" + error.getCode() + ")");
                System.out.println("\tIndex: " + error.getIndex());
                System.out.println("\tMessage: " + error.getMessage());
                System.out.println("\tDetail: " + error.getDetails());
            }

            throw fault;  // To be caught and ignored in main.
        }

        return response.getKeywordLocationResult();
    }
}

Community Additions

Show:
© 2014 Microsoft