Export (0) Print
Expand All

Product Ads in Java

The following example shows how to add a product extension and associate it with a campaign, add product criterion to an ad group, get and update the criterion, and add promotional text to product ads.

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.


package campaign;

import java.rmi.*;
import java.text.*;
import java.util.*;

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

/**
 *
 */
public class ProductAds {

    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>";

    // The advertiser's account ID and customer ID.

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

    // The ID of the campaign and ad group to add the product criterions to.

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

    /**
     */
    public static void main(String[] args) {
        CampaignManagementServiceLocator locator = null;
        long[] adExtensionIds = null;
        long[] productAdIds = null;
        long[] criterionIds = null;
        AdGroupCriterion[] criterions = 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);

            // Create the product extension and associate it with a campaign.

            adExtensionIds = AddProductExtensions(m_accountId);
            AssociateExtensionsWithCampaign(m_accountId, m_campaignId, adExtensionIds[0]);

            // Create a product criterion for the ad group.

            criterionIds = AddProductCriterion(m_accountId, m_adGroupId);
            criterions = GetAdGroupCriterions(m_accountId, criterionIds);
            PrintAdGroupCriterions(criterionIds, criterions);

            // Provide the promotional text that gets added to product ads.

            productAdIds = AddPromotionalText(m_adGroupId);

            // Update the product criterion.

            criterions = GetAdGroupCriterions(m_accountId, m_adGroupId);
            UpdateProductCriterion(m_accountId, criterions);
            criterions = GetAdGroupCriterions(m_accountId, m_adGroupId);
            PrintAdGroupCriterions(criterionIds, criterions);
        }
        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();
            }
        }
    }

    // Adds a product ad extension to the account's ad extension library.
    // The extension is used to associate a campaign with the customer's
    // Bing Merchant Center (BMC) store.

    static long[] AddProductExtensions(long accountId) throws RemoteException, Exception
    {
        AddAdExtensionsRequest request = new AddAdExtensionsRequest();
        AddAdExtensionsResponse response = null;
        long[] ids = null;

        // Specify the extensions.

        AdExtension2[] extensions = new AdExtension2[1];

        ProductAdExtension extension = new ProductAdExtension();
        extension.setName("Basketball Shoes");
        extension.setStoreId((long)<storeidgoeshere>); // Customer's BMC store ID
        extension.setStoreName(null);  // Read-only, must be null

        // Optional filter that identifies the products in the store
        // to advertise. The product is selected if it meets the conditions
        // in collection 1 OR the conditions in collection 2, and so on.
        // If null (no conditions are specified), Bing
        // can create product ads for all products in the store.
        // If the product criterion specifies a filter, the product
        // must also meet the conditions of the criterion filter.

        ProductConditionCollection[] collections = new ProductConditionCollection[2];

        ProductConditionCollection collection = new ProductConditionCollection();

        ProductCondition[] conditions = new ProductCondition[2];
        conditions[0] = new ProductCondition();
        conditions[0].setOperand("ProductType");
        conditions[0].setAttribute("Apparel > Shoes > Basketball > Mens");
        conditions[1] = new ProductCondition();
        conditions[1].setOperand("Brand");
        conditions[1].setAttribute("Speedy Speedsters");

        collection.setConditions(conditions);
        collections[0] = collection;

        collection = new ProductConditionCollection();

        conditions = new ProductCondition[2];
        conditions[0] = new ProductCondition();
        conditions[0].setOperand("ProductType");
        conditions[0].setAttribute("Apparel > Shoes > Basketball > Boys");
        conditions[1] = new ProductCondition();
        conditions[1].setOperand("Brand");
        conditions[1].setAttribute("Speedy Speedsters");

        collection.setConditions(conditions);
        collections[1] = collection;

        extension.setProductSelection(collections);
        extensions[0] = extension;

        // Set the request information.

        request.setAccountId(accountId);
        request.setAdExtensions(extensions);

        try
        {
            response = _service.addAdExtensions(request);

            int idCount = response.getAdExtensionIdentities().length;
            ids = new long[idCount];

            for (int i = 0; i < idCount; i++)
            {
                ids[i] = response.getAdExtensionIdentities()[i].getId();
            }
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("AddAdExtensions 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("AddAdExtensions 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.\n");
                        break;

                    case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element " +
                            "cannot be null or empty.\n");
                        break;

                    case 3862: // CampaignServiceLocationAdExtensionsEntityLimitExceeded
                        System.out.println("The number of location ad extensions in the " +
                            "ad extensions list exceeds the maximum allowed.\n");
                        break;

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

            // This list of errors codes is just a sampling of the possible errors that
            // AddAdExtensions can throw.

            // Note that the Details element of BatchErrors contains the zero-based
            // index of the product collection that caused the error.

            for (BatchError error : fault.getBatchErrors())
            {
                switch (error.getCode())
                {
                    case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To add product extensions, the customer " +
                            "must be a member of the Product Ads pilot program.\n\n");
                        break;

                    case 3864: // CampaignServiceProductAdExtensionTooManyProductConditionCollections
                        System.out.printf("Failed to add product extension #%d. The " +
                            "list of product condition collections is too long.\n\n",
                            error.getIndex());
                        break;

                    case 3865: // CampaignServiceProductAdExtensionTooManyConditions
                        System.out.printf("Failed to add product extension #%d. Product " +
                            "condition collection #%s contains too many conditions.\n\n",
                            error.getIndex(),
                            error.getDetails());
                        break;

                    case 3866: // CampaignServiceProductAdExtensionInvalidStoreId
                        System.out.printf("Failed to add product extension #%d. The store " +
                            "ID is not valid.\n\n",
                            error.getIndex());
                        break;

                    case 3867: // CampaignServiceProductAdExtensionProductConditionsArrayIsNullOrEmpty
                        System.out.printf("Failed to add product extension #%d. Product " +
                            "condition collection #%s cannot be null or empty.\n\n",
                            error.getIndex(),
                            error.getDetails());
                        break;

                    case 3869: // CampaignServiceProductAdExtensionOperandIsInvalid
                        System.out.printf("Failed to add product extension #%d. One of the " +
                            "operands in product condition collection #%s is not valid.\n\n",
                            error.getIndex(),
                            error.getDetails());
                        break;

                    case 3870: // CampaignServiceProductAdExtensionAttributeIsInvalid
                        System.out.printf("Failed to add product extension #%d. One of the " +
                            "attributes in product condition collection #%s is not valid.\n\n",
                            error.getIndex(),
                            error.getDetails());
                        break;

                    case 4116: // CampaignServiceProductConditionAttributeNullOrEmpty
                        System.out.printf("Failed to add product extension #%d. The attributes " +
                            "in product condition collection #%s cannot be null or empty.\n\n",
                            error.getIndex(),
                            error.getDetails());
                        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);
        }

        return ids;
    }

    // Associates the product extension with a campaign. A campaign can be associated
    // with only one product extension.

    static void AssociateExtensionsWithCampaign(long accountId, long campaignId, long extensionId) throws RemoteException, Exception
    {
        SetAdExtensionsToCampaignsRequest request = new SetAdExtensionsToCampaignsRequest();
        SetAdExtensionsToCampaignsResponse response = null;
        AdExtensionIdToCampaignIdAssociation[] associations = new AdExtensionIdToCampaignIdAssociation[1];

        associations[0] = new AdExtensionIdToCampaignIdAssociation();
        associations[0].setAdExtensionId(extensionId);
        associations[0].setCampaignId(campaignId);

        // Set the request information.

        request.setAccountId(accountId);
        request.setAdExtensionIdToCampaignIdAssociations(associations);

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

            System.out.println("SetAdExtensionsToCampaigns 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",
                        error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetail());
                }
            }

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

            System.out.println("SetAdExtensionsToCampaigns 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.\n");
                        break;

                    case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element " +
                            "cannot be null or empty.\n");
                        break;

                    case 1102: //  CampaignServiceInvalidAccountId
                        System.out.println("The account ID is not valid.\n");
                        break;

                    case 3810: //  CampaignServiceAdExtensionIdToCampaignIdAssociationArrayShouldNotBeN
                        System.out.println("The list of ad extension to campaign " +
                            "associations cannot be null or empty.\n");
                        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 1100: //  CampaignServiceInvalidCampaignId
                        System.out.printf("The campaign ID specified in ad extension " +
                            "to campaign association #%d} is not valid.\n\n",
                            error.getIndex());
                        break;

                    case 1397: //  CampaignServiceEditorialGenericError
                        System.out.printf("The ad extension specified in ad extension " +
                            "to campaign association #%d failed editorial review. " +
                            "The term that failed review is \"%s\".\n\n",
                            error.getIndex(),
                            error.getDetails());
                        break;

                    case 3812: //  CampaignServiceInvalidAdExtensionId
                        System.out.printf("The ad extension ID specified in ad " +
                            "extension to campaign association #%d is not valid.\n\n",
                            error.getIndex());
                        break;

                    case 3818: //  CampaignServiceCannotAssignMoreThanOneAdExtensionTypeToAnEntity
                        System.out.printf("The campaign specified in ad extension to " +
                            "campaign association #%d can contain only one extension of " +
                            "the specified type.\n\n",
                            error.getIndex());
                        break;

                    case 3822: //  CampaignServiceSiteLinkAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To call this operation, you must be a " +
                            "member of the site links ad extensions pilot program.\n\n");
                        break;

                    case 3825: //  CampaignServiceDuplicateInAdExtensionIdToCampaignIdAssociations
                        System.out.printf("The list of ad extension to campaign " +
                            "associations contains a duplicate ad extension ID " +
                            "for the same campaign. Association #%d contains the duplicate.\n\n",
                            error.getIndex());
                        break;

                    case 3856: //  CampaignServiceLocationAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To call this operation, the customer must be a " +
                            "member of the location ad extensions pilot program.\n");
                        break;

                    case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To call this operation, the customer must be a " +
                            "member of the call ad extensions pilot program.\n");
                        break;

                    case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To call this operation, the customer " +
                            "must be a member of the Product Ads pilot program.\n");
                        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);
        }
    }

    // Adds a ProductAd to the specified ad group. Do not confuse a ProductAd object with
    // a product ad that the delivery engine generates. A ProductAd is optional. 
    // Its purpose is to provide promotional text that the delivery engine adds to
    // the product ads that it generates and to provide a way to get performance-based
    // reporting (clicks and impressions) for the product ads.

    static long[] AddPromotionalText(long adGroupId) throws RemoteException, Exception
    {
        AddAdsRequest request = new AddAdsRequest();
        AddAdsResponse response = null;

        // Specify the promotional text to add to the ad group. If your only
        // purpose for adding ProductAd objects is to get reporting, set 
        // PromotionalText to null or an empty string. 

        Ad[] ads = new Ad[1];
        ads[0] = new ProductAd();
        ((ProductAd)ads[0]).setPromotionalText("Free shipping on $99 purchases.");

        // Set the request information.

        request.setAdGroupId(adGroupId);
        request.setAds(ads);

        try
        {
            response = _service.addAds(request);

            System.out.println("Added product ads with the following IDs.");

            for (long id : response.getAdIds())
            {
                System.out.println(id);
            }

            System.out.println();
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("AddAds 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.");
                }
                else
                {
                    System.out.printf("Error code: %d (%s)\nMessage: %s\nDetail: %s\n\n",
                        error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetail());
                }
            }

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

            System.out.println("AddAds 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 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element cannot be null or empty.");
                        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 1313: // CampaignServiceDuplicateAd
                        System.out.printf("Product ad #%d is a duplicate of another product ad in the list.\n\n",
                            error.getIndex());
                        break;

                    case 1366: // CampaignServiceAdTypeInvalidForCustomer
                        System.out.println("To add product ads, the customer " +
                            "must be a member of the Product Ads pilot program.\n");
                        break;

                    case 1398: // CampaignServiceProductAdPromotionalTextTooLong
                        System.out.printf("The promotional text of ad #%d is too long.\n\n",
                            error.getIndex());
                        break;

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

            for (EditorialError error : fault.getEditorialErrors())
            {
                switch (error.getCode())
                {
                    default:
                        System.out.printf("Unable to add ad #%d", error.getIndex());
                        System.out.printf("Error code: %s (%d)\nMessage: %s",
                            error.getErrorCode(), error.getCode(), error.getMessage());
                        System.out.printf("Disapproved test: %s\nAppealable: (%s)\nPublisher country: %s",
                            error.getDisapprovedText(), error.getAppealable(), error.getPublisherCountry());
                        break;
                }
            }

            throw new Exception("", fault);
        }

        return response.getAdIds();
    }

    // Add the product criterions to the ad group. The criterions specify the
    // bid value and optional product conditions filter.

    static long[] AddProductCriterion(long accountId, long adGroupId) throws RemoteException, Exception
    {
        AddAdGroupCriterionsRequest request = new AddAdGroupCriterionsRequest();
        AddAdGroupCriterionsResponse response = null;

        // Specify the product criterions. The product ad gets served if the product
        // matches the criterion's filter AND the product ad extension filter.

        AdGroupCriterion[] criterions = new AdGroupCriterion[2];
        criterions[0] = new BiddableAdGroupCriterion();

        ((BiddableAdGroupCriterion)criterions[0]).setAdGroupId(adGroupId);
        ((BiddableAdGroupCriterion)criterions[0]).setDestinationUrl(null); // Overrides the product store's destination URL
        ((BiddableAdGroupCriterion)criterions[0]).setParam1(null);         // Substitution strings for DestinationUrl
        ((BiddableAdGroupCriterion)criterions[0]).setParam2(null);
        ((BiddableAdGroupCriterion)criterions[0]).setParam3(null);

        ((BiddableAdGroupCriterion)criterions[0]).setCriterionBid(new FixedBid("FixedBid", new Bid(1.05)));

        ProductCondition[] conditions = new ProductCondition[1];
        conditions[0] = new ProductCondition();
        conditions[0].setOperand("SKU");
        conditions[0].setAttribute("11EEE");
        ((BiddableAdGroupCriterion)criterions[0]).setCriterion(new Product("Product", conditions));

        criterions[1] = new BiddableAdGroupCriterion();

        ((BiddableAdGroupCriterion)criterions[1]).setAdGroupId(adGroupId);

        // Default to the ad group's exact-match bid value

        ((BiddableAdGroupCriterion)criterions[1]).setCriterionBid(new FixedBid("FixedBid", new Bid(null)));

        conditions = new ProductCondition[1];
        conditions[0] = new ProductCondition();
        conditions[0].setOperand("SKU");
        conditions[0].setAttribute("11EEE");
        ((BiddableAdGroupCriterion)criterions[1]).setCriterion(new Product("Product", conditions));

        // Set the request information.

        request.setAccountId(accountId);
        request.setAdGroupCriterions(criterions);

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

            System.out.println("AddAdGroupCriterions 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.");
                }
                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("AddAdGroupCriterions failed with the following faults:\n");

            for (OperationError error : fault.getOperationErrors())
            {
                switch (error.getCode())
                {
                    case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element cannot " +
                            "be null or empty.\n");
                        break;

                    case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To add ad group criterions, the customer " +
                            "must be a member of the Product Ads pilot program.\n");
                        break;

                    case 4104: // CampaignServiceAdGroupCriterionsNullOrEmpty
                        System.out.println("To list of ad group criterions cannot be null or empty.\n");
                        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 1515: // CampaignServiceBidAmountsLessThanFloorPrice
                        System.out.printf("The bid value of ad group criterion #%d is " +
                            "less than the minimum allowed bid value.\n\n",
                            error.getIndex());
                        break;

                    case 1516: // CampaignServiceBidAmountsGreaterThanCeilingPrice
                        System.out.printf("The bid value of ad group criterion #%d exceeds " +
                            "the maximum allowed bid value.\n\n",
                            error.getIndex());
                        break;

                    case 3869: // CampaignServiceProductAdExtensionOperandIsInvalid
                        System.out.printf("Product operand #%s of ad group criterion #%d " +
                            "is not valid.\n\n",
                            error.getDetails(),
                            error.getIndex());
                        break;

                    case 3870: // CampaignServiceProductAdExtensionAttributeIsInvalid
                        System.out.printf("Product attribute #%s of ad group criterion #%d " +
                            "is not valid.\n\n",
                            error.getDetails(),
                            error.getIndex());
                        break;

                    case 3872: // CampaignServiceProductConditionDuplicateOperand
                        System.out.printf("Ad group criterion #%s contains duplicate product operands. " +
                            "Product operand #%d is a duplicate.\n\n",
                            error.getDetails(),
                            error.getIndex());
                        break;

                    case 4108: // CampaignServiceAdGroupCriterionInvalidBidType
                        System.out.printf("The bid of ad group criterion #%d is null or " +
                            "is of the wrong type.\n\n",
                            error.getIndex());
                        break;

                    case 4109: // CampaignServiceAdGroupCriterionInvalidBidValue
                        System.out.printf("The bid value of ad group criterion #%d is not valid.\n\n",
                            error.getIndex());
                        break;

                    case 4113: // CampaignServiceProductAdGroupCriterionTooManyConditions
                        System.out.printf("The list of product conditions of ad group " +
                            "criterion #%d is too long.\n\n",
                            error.getIndex());
                        break;

                    default:
                        System.out.printf("Unable to add ad group criterion #%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);
        }

        return response.getAdGroupCriterionIds();
    }

    // Gets the specified list of ad group criterions.

    static AdGroupCriterion[] GetAdGroupCriterions(long accountId, long[] adGroupCriterionIds) throws RemoteException, Exception
    {
        GetAdGroupCriterionsByIdsRequest request = new GetAdGroupCriterionsByIdsRequest();
        GetAdGroupCriterionsByIdsResponse response = null;

        // Set the request information.

        request.setAccountId(accountId);
        request.setAdGroupCriterionIds(adGroupCriterionIds);

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

            System.out.println("GetAdGroupCriterionsByIds 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.");
                }
                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("GetAdGroupCriterionsByIds failed with the following faults:\n");

            for (OperationError error : fault.getOperationErrors())
            {
                switch (error.getCode())
                {
                    case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element cannot be null or empty.\n");
                        break;

                    case 4101: //  CampaignServiceAdGroupCriterionIdArrayNullOrEmpty
                        System.out.println("The list of ad group criterion IDs cannot be null or empty.\n");
                        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())
                {
                    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.getAdGroupCriterions();
    }

    // Gets all criterion of the specified type from the ad group.

    static AdGroupCriterion[] GetAdGroupCriterions(long accountId, long adGroupId) throws RemoteException, Exception
    {
        GetAdGroupCriterionsByAdGroupIdRequest request = new GetAdGroupCriterionsByAdGroupIdRequest();
        GetAdGroupCriterionsByAdGroupIdResponse response = null;

        // Set the request information.

        request.setAccountId(accountId);
        request.setAdGroupId(adGroupId);
        request.setCriterionTypeFilter(new String[] { CriterionTypeNull._Product });

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

            System.out.println("GetAdGroupCriterionsByAdGroupId 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.");
                }
                else
                {
                    System.out.printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n",
                        error.getErrorCode(), error.getCode(), error.getMessage(), error.getDetail());
                }
            }

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

            System.out.println("GetAdGroupCriterionsByAdGroupId 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 1102: //  CampaignServiceInvalidAccountId
                        System.out.println("The account ID is not valid.");
                        break;

                    case 1201: //  CampaignServiceInvalidAdGroupId
                        System.out.println("The ad group ID is not valid.");
                        break;

                    case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element cannot be null or empty.");
                        break;

                    case 4115: //  CampaignServiceInvalidAdGroupCriterionCriterionTypeFilter
                        System.out.println("The criterion type filter cannot 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())
                {
                    default:
                        System.out.printf("Error code: %s (%d)\nIndex: %d\nMessage: %s\nDetail: %s\n",
                            error.getErrorCode(), error.getCode(), error.getIndex(), error.getMessage(), error.getDetails());
                        break;
                }
            }

            throw new Exception("", fault);
        }

        return response.getAdGroupCriterions();
    }

    // Updates the criterions in the ad group. Any field not set
    // to null is updated.

    private static void UpdateProductCriterion(long accountId, AdGroupCriterion[] criterions) throws RemoteException, Exception
    {
        UpdateAdGroupCriterionsRequest request = new UpdateAdGroupCriterionsRequest();
        UpdateAdGroupCriterionsResponse response = null;
        ArrayList<AdGroupCriterion> updatedCriterions = new ArrayList<AdGroupCriterion>();

        for (AdGroupCriterion criterion : criterions)
        {
            if (criterion instanceof BiddableAdGroupCriterion)
            {
                if (((BiddableAdGroupCriterion)criterion).getCriterionBid() instanceof FixedBid)
                {
                    // Increase the bid by 20 percent if the criterion's bid amount
                    // is not set to null (a null bid amount indicates that the
                    // criterion uses the ad group's exact-match bid value).

                    if (null != ((FixedBid)((BiddableAdGroupCriterion)criterion).getCriterionBid()).getBid().getAmount())
                    {
                        BiddableAdGroupCriterion update = new BiddableAdGroupCriterion();

                        update.setId(criterion.getId());                // Required
                        update.setAdGroupId(criterion.getAdGroupId());  // Required

                        // Update status if you want to Pause, Resume, or Delete the criterion.

                        update.setStatus(null);  // AdGroupCriterionStatus.Paused;

                        double currentBid = ((FixedBid)((BiddableAdGroupCriterion)criterion).getCriterionBid()).getBid().getAmount();
                        update.setCriterionBid(new FixedBid("FixedBid", new Bid(currentBid * 1.20)));

                        ((BiddableAdGroupCriterion)update).setDestinationUrl(null);
                        ((BiddableAdGroupCriterion)update).setParam1(null);
                        ((BiddableAdGroupCriterion)update).setParam2(null);
                        ((BiddableAdGroupCriterion)update).setParam3(null);

                        // If you don't want to update the criterion, set Criterion to null.
                        // To remove all conditions, set Conditions to an empty list. For example,

                        update.setCriterion(null);

                        updatedCriterions.add(update);
                    }
                }
            }
        }

        if (0 == updatedCriterions.size())
        {
            return; // Nothing to update
        }

        // Set the request information.

        request.setAccountId(accountId);
        request.setAdGroupCriterions(updatedCriterions.toArray(new AdGroupCriterion[updatedCriterions.size()]));

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

            System.out.println("UpdateAdGroupCriterions 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("UpdateAdGroupCriterions failed with the following faults:\n");

            for (OperationError error : fault.getOperationErrors())
            {
                switch (error.getCode())
                {
                    case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                        System.out.println("The CustomerAccountId header element cannot be null or empty.\n");
                        break;

                    case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                        System.out.println("To add ad group criterions, the customer " +
                            "must be a member of the Product Ads pilot program.\n");
                        break;

                    case 4104: // CampaignServiceAdGroupCriterionsNullOrEmpty
                        System.out.println("To list of ad group criterions cannot be null or empty.\n");
                        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 1515: // CampaignServiceBidAmountsLessThanFloorPrice
                        System.out.printf("The bid value of ad group criterion #%d is " +
                            "less than the minimum allowed bid value.\n\n",
                            error.getIndex());
                        break;

                    case 1516: // CampaignServiceBidAmountsGreaterThanCeilingPrice
                        System.out.printf("The bid value of ad group criterion #%d " +
                            "exceeds the maximum allowed bid value.\n",
                            error.getIndex());
                        break;

                    case 3869: // CampaignServiceProductAdExtensionOperandIsInvalid
                        System.out.printf("Product operand #%s of ad group criterion " +
                            "#{1} is not valid.\n\n",
                            error.getDetails(),
                            error.getIndex());
                        break;

                    case 3870: // CampaignServiceProductAdExtensionAttributeIsInvalid
                        System.out.printf("Product attribute #%s of ad group criterion " +
                            "#%d is not valid.\n\n",
                            error.getDetails(),
                            error.getIndex());
                        break;

                    case 3872: // CampaignServiceProductConditionDuplicateOperand
                        System.out.printf("Ad group criterion #%s contains duplicate product operands. " +
                            "Product operand #%d is a duplicate.\n\n",
                            error.getDetails(),
                            error.getIndex());
                        break;

                    case 4108: // CampaignServiceAdGroupCriterionInvalidBidType
                        System.out.printf("The bid of ad group criterion #%d is null " +
                            "or is of the wrong type.\n\n",
                            error.getIndex());
                        break;

                    case 4109: // CampaignServiceAdGroupCriterionInvalidBidValue
                        System.out.printf("The bid value of ad group criterion " +
                            "#%d is not valid.\n\n",
                            error.getIndex());
                        break;

                    case 4113: // CampaignServiceProductAdGroupCriterionTooManyConditions
                        System.out.printf("The list of product conditions of ad group " +
                            "criterion #%d is too long.\n\n",
                            error.getIndex());
                        break;

                    default:
                        System.out.printf("Unable to add ad group criterion #%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);
        }
    }

    // Prints the details of the criterion.

    private static void PrintAdGroupCriterions(long[] criterionIds, AdGroupCriterion[] criterions)
    {
        int i = 0;
        NumberFormat currencyFmt = NumberFormat.getCurrencyInstance();

        for (AdGroupCriterion adGroupCriterion : criterions)
        {
            if (null != adGroupCriterion)
            {
                if (adGroupCriterion instanceof BiddableAdGroupCriterion)
                {
                    BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion)adGroupCriterion;

                    System.out.println("Biddable criterion ID: " + biddableCriterion.getId());

                    if (biddableCriterion.getCriterionBid() instanceof FixedBid)
                    {
                        if (null == ((FixedBid)biddableCriterion.getCriterionBid()).getBid().getAmount())
                        {
                            System.out.println("  Bid amount: Uses the ad group's exact-match bid value");
                        }
                        else
                        {
                            System.out.printf("  Bid amount: %s\n",
                                currencyFmt.format(((FixedBid)biddableCriterion.getCriterionBid()).getBid().getAmount()));
                        }
                    }

                    System.out.println("  Destination URL: " + biddableCriterion.getDestinationUrl());
                    System.out.println("  Param1: " + biddableCriterion.getParam1());
                    System.out.println("  Param2: " + biddableCriterion.getParam2());
                    System.out.println("  Param3: " + biddableCriterion.getParam3());
                    System.out.println("  Status: " + biddableCriterion.getStatus());
                    System.out.println("  Editorial status: " + biddableCriterion.getEditorialStatus());

                    if (biddableCriterion.getCriterion() instanceof Product)
                    {
                        System.out.print("  Product conditions: ");

                        int length = ((Product)biddableCriterion.getCriterion()).getConditions().length;

                        if (length > 0)
                        {
                            for (int j = 0; j < length; j++)
                            {
                                System.out.printf("%s=%s%s", ((Product)biddableCriterion.getCriterion()).getConditions()[j].getOperand(),
                                    ((Product)biddableCriterion.getCriterion()).getConditions()[j].getAttribute(),
                                    (j + 1 < length) ? " AND " : "\n\n");
                            }
                        }
                        else
                        {
                            System.out.println("No product filter applied.\n");
                        }
                    }
                }
            }
            else
            {
                System.out.printf("Ad group criterion %d was not found.\n\n", criterionIds[i]);
            }

            i++;
        }
    }

}

Community Additions

Show:
© 2015 Microsoft