Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Get Historical Performance in Java

The following example shows how to get the historical bid and traffic performance of one or more keywords used in search queries using the Ad Intelligence GetHistoricalKeywordPerformanceByDevice 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 GetPerformanceByDevice
//

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

/**
 *
 */
public class GetPerformanceByDevice {

    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;
        KeywordHistoricalPerformanceByDevice[] performances = null;
        NumberFormat currencyFmt = NumberFormat.getCurrencyInstance();

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

            performances = GetPerformances(m_accountId);

            if (performances != null)
            {
                for (KeywordHistoricalPerformanceByDevice performance : performances)
                {
                    System.out.print(performance.getKeyword());

                    if (null == performance.getDevice())
                    {
                        System.out.println("\n  There is no historical performance data available for the keyword.\n");
                    }
                    else
                    {
                        System.out.printf(" (%s)\n", performance.getDevice());

                        for (KeywordKPI kpi : performance.getKeywordKPIs())
                        {
                            System.out.println("  " + kpi.getMatchType());
                            System.out.println("    Ad Position: " + kpi.getAdPosition());
                            System.out.println("    Average Bid: " + currencyFmt.format(kpi.getAverageBid()));
                            System.out.println("    Average CPC: " + currencyFmt.format(kpi.getAverageCPC()));
                            System.out.println("    Total Cost: " + currencyFmt.format(kpi.getTotalCost()));
                            System.out.printf("    Clicks: %d\n", kpi.getClicks());
                            System.out.printf("    CTR: %.2f%%\n", kpi.getCTR());
                            System.out.printf("    Impressions: %,d\n\n", kpi.getImpressions());
                        }
                    }
                }
            }
        }
        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 historical performance of the specified keywords.
     * The performance is broken out by device type and match type.
     */

    public static KeywordHistoricalPerformanceByDevice[] GetPerformances(long accountId) throws RemoteException
    {
        GetHistoricalKeywordPerformanceByDeviceRequest request = new GetHistoricalKeywordPerformanceByDeviceRequest();
        GetHistoricalKeywordPerformanceByDeviceResponse 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.setMatchTypes(new MatchType[] { MatchType.Broad, MatchType.Phrase, MatchType.Exact});
        request.setTargetAdPosition(AdPosition.MainLine1);
        request.setTimeInterval(TimeInterval.Last7Days);

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

            System.out.println("getHistoricalKeywordPerformanceByDevice 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("getHistoricalKeywordPerformanceByDevice 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 3409: // CampaignServiceInvalidMatchTypes
                        System.out.println("The list of match types cannot be null or empty.");
                        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 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.getKeywordHistoricalPerformances();
    }
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.