Export (0) Print
Expand All

Target Devices in Java

The following example shows how to target specific devices and operating systems 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 DeviceTargeting
// 

import java.rmi.*;

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

/**
 *
 */
public class DeviceTargeting {

    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 that you want to target to specific devices.
// The campaign must already be associated with a target.

    private static long m_campaignId = <campaignidgoeshere>;

    /**
     * 
     */
    public static void main(String[] args) {
        CampaignManagementServiceLocator locator = null;
        Target[] targets = 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);

            targets = GetCampaignTargets(m_campaignId);

            if (null == targets[0])
            {
                System.out.printf("Campaign %d is not associated with a target.\n", m_campaignId);
            }
            else
            {
                // Indexing targets array because a campaign can be associated
                // with only one target object.

                PrintDeviceTargets((long)targets[0].getId());
                TargetDevices((long)targets[0].getId());
                PrintDeviceTargets((long)targets[0].getId());
                RemoveDeviceTarget((long)targets[0].getId());
                PrintDeviceTargets((long)targets[0].getId());
            }
        }
        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();
            }
        }
    }

    // Gets the target associated with the specified campaign. Because most
    // campaigns target a location, this example assumes that the campaign is
    // already associated with a target object.

    // If the campaign is not associated with a target, you would need to create a
    // Target object that sets the Device element to computers or smartphones
    // (it doesn't matter which one). After calling the AddTargetsToLibrary
    // operation to add the target to the target library, you would call the
    // SetTargetToCampaign operation to associate the target with the campaign.

    static Target[] GetCampaignTargets(long campaignId) throws RemoteException, Exception
    {
        GetTargetsByCampaignIdsRequest request = new GetTargetsByCampaignIdsRequest();
        GetTargetsByCampaignIdsResponse response = null;

        // Set the request information.

        request.setCampaignIds(new long[] { campaignId });

        try
        {
            System.out.printf("Getting target associated with campaign %d.\n", campaignId);

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

            System.out.println("GetTargetsByCampaignIds 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("GetTargetsByCampaignIds 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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                        System.out.println("The CustomerId header element cannot be null or empty.");
                        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())
                {
                    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.getTargets();
    }

    // To target devices or operating systems, call the UpdateDeviceOSTargets
    // operation. Because the operation overwrites the current list
    // of devices being targeted, you must specify all devices to target.

    // This example targets only smartphones running the Windows operation system.
    // To target all operating systems of a device type, set OSName to null.
    // If DeviceName is set to Computers, OSName must be set to null.

    static void TargetDevices(long targetId) throws RemoteException, Exception
    {
        UpdateDeviceOSTargetsRequest request = new UpdateDeviceOSTargetsRequest();
        UpdateDeviceOSTargetsResponse response = null;

        // Define devices and operating systems to target.

        TargetAssociation[] targets = new TargetAssociation[1];
        targets[0] = new TargetAssociation();
        targets[0].setDeviceOSTarget(new DeviceOSTarget());
        targets[0].getDeviceOSTarget().setDeviceOSList(new DeviceOS[1]);
        targets[0].getDeviceOSTarget().getDeviceOSList()[0] = new DeviceOS();
        targets[0].getDeviceOSTarget().getDeviceOSList()[0].setDeviceName("Smartphones");
        targets[0].getDeviceOSTarget().getDeviceOSList()[0].setOSName("Windows");
        targets[0].setId(targetId);

        // Set the request information.

        request.setTargetAssociations(targets);

        try
        {
            response = _service.updateDeviceOSTargets(request);
            System.out.printf("Added device OS targets to target %d.\n", targetId);
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("UpdateDeviceOSTargets 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("UpdateDeviceOSTargets 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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                        System.out.println("The CustomerId 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 2922: //  CampaignServiceInvalidDeviceTarget
                        System.out.println("The device name and/or operating system name is not valid. " +
                            "The name cannot be null or empty and must be one of the predefined names. " +
                            "In addition, the combination of device name and operating system must be valid.\n");
                        break;

                    case 2923: //  CampaignServiceDuplicateDeviceTarget
                        System.out.println("The list of devices cannot contain duplicate device and operating system combinations.\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);
        }
    }

    // Gets the target associated with the specified campaign and prints the devices
    // and operating systems that it targets.

    static void PrintDeviceTargets(long targetId) throws RemoteException, Exception
    {
        TargetAssociation[] deviceTargets = null;

        deviceTargets = GetDeviceTargets((long)targetId);

        if (null == deviceTargets[0].getDeviceOSTarget())
        {
            System.out.println("The campaign targets all devices.");
        }
        else
        {
            System.out.println("The campaign targets the following devices.");

            for (TargetAssociation deviceTarget : deviceTargets)
            {
                for (DeviceOS device : deviceTarget.getDeviceOSTarget().getDeviceOSList())
                {
                    System.out.printf("  %s - %s\n",
                        device.getDeviceName(),
                        (null == device.getOSName()) ? "All operating systems" : device.getOSName());
                }
            }
        }
    }

    // Gets the list of devices and operating systems being targeted.

    static TargetAssociation[] GetDeviceTargets(long targetId) throws RemoteException, Exception
    {
        GetDeviceOSTargetsByIdsRequest request = new GetDeviceOSTargetsByIdsRequest();
        GetDeviceOSTargetsByIdsResponse response = null;

        // Set the request information.

        request.setTargetIds(new long[] { targetId });

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

            System.out.println("GetDeviceOSTargetsByIds 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("GetDeviceOSTargetsByIds 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 206: //  NullArrayArgument
                        System.out.println("The list of targets IDs cannot be null or empty.");
                        break;

                    case 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                        System.out.println("The CustomerId 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())
                {
                    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.getTargetAssociations();
    }

    // Removes the device targeting from the target object.

    static void RemoveDeviceTarget(long targetId) throws RemoteException, Exception
    {
        UpdateTargetsInLibraryRequest request = new UpdateTargetsInLibraryRequest();
        UpdateTargetsInLibraryResponse response = null;

        Target[] targets = GetTarget(targetId);

        targets[0].setIsLibraryTarget(null);
        targets[0].setDevice(null);

        // Set the request information.

        request.setTargets(targets);

        try
        {
            response = _service.updateTargetsInLibrary(request);
            System.out.printf("Removed device targeting from target %d.\n", targetId);
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("UpdateTargetsInLibrary 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("UpdateTargetsInLibrary 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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                        System.out.println("The CustomerId 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())
                {
                    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);
        }
    }

    // Get the specified target from the library.

    static Target[] GetTarget(long targetId) throws RemoteException, Exception
    {
        GetTargetsByIdsRequest request = new GetTargetsByIdsRequest();
        GetTargetsByIdsResponse response = null;

        // Set the request information.

        request.setTargetIds(new long[] { targetId });
        request.setLocationTargetVersion("Latest");

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

            System.out.println("GetTargetsByIds 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("GetTargetsByIds 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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                        System.out.println("The CustomerId 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())
                {
                    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.getTargets();
    }
}

Community Additions

Show:
© 2015 Microsoft