Ad Rotation in Java

The following example shows how to get and set the ad rotation of an ad group using the following Campaign 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 SetAdRotation
// 

import java.rmi.*;

import bingads.campaignmanagement.*;
import bingads.campaignmanagement.adapi.*;
//import bingads.campaignmanagement.datacontracts.*;

/**
 *
 */
public class SetAdRotation {

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

    // API credentials.

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

    // Advertiser's account ID and customer ID.

    private static long m_accountId = <accountidgoeshere>;
    private static long m_customerId = <customeridgoeshere>;

    // Ad group to apply the rotation policy to.

    private static long m_campaignId = <campaignidgoeshere>;
    private static long m_adGroupId = <adgroupidgoeshere>;


    /**
     */
    public static void main(String[] args) {
        CampaignManagementServiceLocator locator = null;
        AdRotation[] adRotations = null;

        try
        {
            locator = new CampaignManagementServiceLocator();
            _namespace = locator.getServiceName().getNamespaceURI();
            _service = (BasicHttpBinding_ICampaignManagementServiceStub) locator.getBasicHttpBinding_ICampaignManagementService();

            // Set the header properties.

            _service.clearHeaders();
            _service.setHeader(_namespace, "CustomerId", m_customerId);
            _service.setHeader(_namespace, "CustomerAccountId", m_accountId);
            _service.setHeader(_namespace, "DeveloperToken", m_token);
            _service.setHeader(_namespace, "UserName", m_username);
            _service.setHeader(_namespace, "Password", m_password);

            SetAdRotation(m_campaignId, m_adGroupId, AdRotationType.RotateAdsEvenly);

            adRotations = GetAdRotation(m_campaignId, m_adGroupId);

            for (AdRotation adRotation : adRotations)
            {
                System.out.printf("Ad group %d rotates %s.\n",
                    m_adGroupId,
                    (adRotation.getType().equals(AdRotationType.OptimizeForClicks)) ?
                        "best performing ads" : "ads evenly");
            }
        }
        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 EditorialApiFaultDetail ||
                 e.getCause() instanceof ApiFaultDetail )
            {
                ;
            }
            else
            {
                System.out.println("Error encountered: ");
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    // Set the type of ad rotation to use for the specified ad group.

    static void SetAdRotation(
        long campaignId,
        long adGroupId,
        AdRotationType rotationType) throws RemoteException, Exception
    {
        SetAdRotationToAdGroupsRequest request = new SetAdRotationToAdGroupsRequest();
        SetAdRotationToAdGroupsResponse response = null;

        // Specify the extensions.

        AdExtension2[] extensions = new AdExtension2[3];

        extensions[0] = new SiteLinksAdExtension();
        SiteLink[] siteLinks = new SiteLink[1];
        siteLinks[0] = new SiteLink();
        siteLinks[0].setDestinationUrl("AplineSkiHouse.com/WinterGloveSale");
        siteLinks[0].setDisplayText("Winter Glove Sale");
        ((SiteLinksAdExtension)extensions[0]).setSiteLinks(siteLinks);


        AdGroupAdRotation[] rotations = new AdGroupAdRotation[1];

        rotations[0] = new AdGroupAdRotation();
        rotations[0].setAdGroupId(adGroupId);
        rotations[0].setAdRotation(new AdRotation());
        rotations[0].getAdRotation().setType(rotationType);
        rotations[0].getAdRotation().setStartDate(null);  // The start and end dates must be null.
        rotations[0].getAdRotation().setEndDate(null);

        // Set the request information.

        request.setCampaignId(campaignId);
        request.setAdGroupAdRotations(rotations);

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

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

            for (AdApiError error : fault.getErrors())
            {
                if (105 == error.getCode()) //  InvalidCredentials
                {
                    System.out.println("The specified credentials are not valid " +
                        "or the account is inactive.\n");
                }
                else
                {
                    System.out.printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                        error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetail());
                }
            }

            throw new Exception("", fault);
        }
        catch (ApiFaultDetail fault)
        {
            // Log this fault.

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

            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 1100: //  CampaignServiceInvalidCampaignId
                        System.out.printf("The campaign ID %d is not valid.\n",
                            campaignId);
                        break;

                    case 1201: //  CampaignServiceInvalidAdGroupId
                        System.out.println("All AdGroupAdRotation objects must specify an ad group ID.");
                        break;

                    case 1261: //  CampaignServiceAdGroupAdRotationArrayShouldNotBeNullOrEmpty
                        System.out.println("The list of AdGroupAdRotations cannot be null or emtpy.");
                        break;

                    case 1263: //  CampaignServiceCannotSetStartOrEndDateForAdRotation
                        System.out.println("The start and end dates must be null.");
                        break;

                    default:
                        System.out.printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                            error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetails());
                        break;
                }
            }

            for (BatchError error : fault.getBatchErrors())
            {
                switch (error.getCode())
                {
                        case 1201: //  CampaignServiceInvalidAdGroupId
                            System.out.printf("The ad group ID %d specified in AdGroupAdRotations[%d] is not valid.\n\n",
                                request.getAdGroupAdRotations()[error.getIndex()].getAdGroupId(),
                                error.getIndex());
                            break;

                        case 1214: //  CampaignServiceCannotCreateDuplicateAdGroup
                            System.out.printf("The list of AdGroupRotations must contain unique ad group IDs; " +
                                "ad group ID %d specified in AdGroupAdRotations[%d] already exists in the list.\n\n",
                                request.getAdGroupAdRotations()[error.getIndex()].getAdGroupId(),
                                error.getIndex());
                            break;

                    default:
                        System.out.printf("Unable to add extension #%d\n", error.getIndex());
                        System.out.printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                            error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetails());
                        break;
                }
            }

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

    // Gets the specified ad extensions from the account's library
    // and prints their contents.

    static AdRotation[] GetAdRotation(long campaignId, long adGroupId) throws RemoteException, Exception
    {
        GetAdRotationByAdGroupIdsRequest request = new GetAdRotationByAdGroupIdsRequest();
        GetAdRotationByAdGroupIdsResponse response = null;

        // Set the request information.

        request.setCampaignId(campaignId);
        request.setAdGroupIds(new long[] { adGroupId });

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

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

            for (AdApiError error : fault.getErrors())
            {
                if (105 == error.getCode()) //  InvalidCredentials
                {
                    System.out.println("The specified credentials are not valid " +
                        "or the account is inactive.\n");
                }
                else
                {
                    System.out.printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                        error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetail());
                }
            }

            throw new Exception("", fault);
        }
        catch (ApiFaultDetail fault)
        {
            // Log this fault.

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

            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 1218: //  CampaignServiceAdGroupIdsArrayShouldNotBeNullOrEmpty
                        System.out.println("The list of ad group IDs cannot be null or empty.");
                        break;

                    default:
                        System.out.printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n",
                            error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetails());
                        break;
                }
            }

            for (BatchError error : fault.getBatchErrors())
            {
                switch (error.getCode())
                {
                    case 1201: //  CampaignServiceInvalidAdGroupId
                        System.out.printf("The ad group ID {0} is not valid.\n\n",
                            request.getAdGroupIds()[error.getIndex()]);
                        break;

                    case 1203: //  CampaignServiceDuplicateInAdGroupIds
                        System.out.printf("The list of ad group IDs must be unique; " +
                            "ad group ID {0} already exists in the list.\n\n",
                            request.getAdGroupIds()[error.getIndex()]);
                        break;

                    default:
                        System.out.printf("Error code: %s (%d)\nIndex: %d\nMessage: %s\nDetail: %s\n\n",
                                error.getErrorCode(), error.getCode(), error.getIndex(), error.getMessage(), error.getDetails());
                        break;
                }
            }

            throw new Exception("", fault);
        }

        return response.getAdRotationByAdGroupIds();
    }
}

Community Additions

Show: