Get Keyword Search Count in Java

The following example shows how to get a count of the number of search queries that included the specified keywords using the Ad Intelligence GetHistoricalSearchCountByDevice 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 GetSearchCounts
//

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

/**
 *
 */
public class GetSearchCounts {

    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;
        KeywordSearchCountByDevice[] counts = null;

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

            counts = GetCounts(m_accountId);

            if (counts != null)
            {
                for (KeywordSearchCountByDevice count : counts)
                {
                    System.out.print(count.getKeyword());

                    if (null == count.getDevice())
                    {
                        System.out.println("\n  No count data available for the specified device types.\n");
                    }
                    else
                    {
                        System.out.printf(" (%s)\n", count.getDevice());

                        for (HistoricalSearchCountPeriodic kpi : count.getHistoricalSearchCounts())
                        {
                            System.out.printf("  %d/%d/%d  %,d\n",
                                    kpi.getDayMonthAndYear().getMonth(),
                                    kpi.getDayMonthAndYear().getDay(),
                                    kpi.getDayMonthAndYear().getYear(),
                                    kpi.getSearchCount());
                        }

                        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 count of the number of times a user searched for the specified keywords.
     * The performance is broken out by device type and date.
     */

    public static KeywordSearchCountByDevice[] GetCounts(long accountId) throws RemoteException
    {
        GetHistoricalSearchCountByDeviceRequest request = new GetHistoricalSearchCountByDeviceRequest();
        GetHistoricalSearchCountByDeviceResponse 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.setDevices(new String[] { "Smartphones", "Computers", "NonSmartphones" });
        request.setLanguage("English");
        request.setPublisherCountries(new String[] { "US" });
        request.setTimePeriodRollup("Daily");

        request.setStartTimePeriod(new DayMonthAndYear());
        request.getStartTimePeriod().setMonth(2);
        request.getStartTimePeriod().setDay(1);
        request.getStartTimePeriod().setYear(2012);

        request.setEndTimePeriod(new DayMonthAndYear());
        request.getEndTimePeriod().setMonth(2);
        request.getEndTimePeriod().setDay(14);
        request.getEndTimePeriod().setYear(2012);

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

            System.out.println("getHistoricalSearchCountByDevice 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("getHistoricalSearchCountByDevice 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 3405: // CampaignServiceInvalidEndDate
                        System.out.println("The end date cannot be later than today.");
                        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 3416: // CampaignServiceServiceInvalidRollupPeriod
                        System.out.println("The specified aggregation value is not valid.");
                        break;

                    case 3417: // CampaignServiceInvalidDevice
                        System.out.println("One or more of the specified devices is not valid.");
                        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.getKeywordSearchCounts();
    }
}

Community Additions

Show: