Export (0) Print
Expand All

Add Targets in Java

The following example shows how to add a target to a customer’s library that can be used to incrementally increase bids based on age, day, gender, hour, and location using the Campaign Management AddTargetsToLibrary 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 MyCreateTargets username password developertoken
// 

import java.io.*;
import java.util.*;
import java.net.URL;
import bingads.campaignmanagement.*;
import bingads.campaignmanagement.adapi.*;
import bingads.campaignmanagement.datacontracts.*;

public class MyCreateTargets
{
    public static void main(String[] args)
    {
        // Application-specific values.
        // Application-specific value.
        java.lang.Long accountId = new Long(<youraccountid>); 
        java.lang.Long customerId = new Long(<yourcustomerid>);

        // The Microsoft Bing Ads API namespace,
        // which is used in the SOAP header.
        String namespace = 
            "https://adcenter.microsoft.com/v8";

        // Update the URL as needed for the corresponding environment.
        // This example URL is for the sandbox environment.
        String url = "https://api.sandbox.bingads.microsoft.com/Api/Advertiser/v8/CampaignManagement/CampaignManagementService.svc?wsdl";
        // The following is the production environment URL.
        // String url = "https://adcenterapi.microsoft.com/Api/Advertiser/v8/CampaignManagement/CampaignManagementService.svc?wsdl";

        ICampaignManagementService campaignManagement = null;

        CampaignManagementServiceLocator campaignServiceLocator = null;

        BasicHttpBinding_ICampaignManagementServiceStub stub = null;

        AddTargetsToLibraryRequest addTargetsToLibraryRequest = null;
        AddTargetsToLibraryResponse addTargetsToLibraryResponse = null;

        Target[] targets = null;

        try
        {
            if (args.length != 3)
            {
                // This application expects the user name, password, and
                // developer token to be passed in as command-line arguments.
                System.out.println("Correct usage:");
                System.out.print("java MyCreateTargets ");
                System.out.println("user_name password developertoken");
                System.exit(-1);
            }

            campaignServiceLocator = new
              CampaignManagementServiceLocator();

            campaignServiceLocator.setBasicHttpBinding_ICampaignManagementServiceEndpointAddress(url);

            campaignManagement =
             campaignServiceLocator.getBasicHttpBinding_ICampaignManagementService();

            stub = (BasicHttpBinding_ICampaignManagementServiceStub)
                          campaignManagement;

            // Assign values for the credentials and the developer token.
            // args[0] is the user name.
            // args[1] is the password.
            // args[2] is the developer token.
            // The application token is reserved for future use and 
            // does not need to be assigned a value.

            stub.setHeader(namespace,
                     "ApplicationToken", "");
            stub.setHeader(namespace,
                     "DeveloperToken", args[2]);
            stub.setHeader(namespace,
                     "UserName", args[0]);
            stub.setHeader(namespace,
                     "Password", args[1]);
            stub.setHeader(namespace,
                     "CustomerAccountId", accountId);
            stub.setHeader(namespace,
                     "CustomerId", customerId);

            // This example sets up a target for Age, Day, 
            // Gender, Hour, and State.
            targets = new Target[1];
            targets[0] = new Target();
            
            // Bid incrementally on two age ranges.
            AgeTargetBid[] ageTargetBids = new AgeTargetBid[2];
            ageTargetBids[0] = new AgeTargetBid();
            ageTargetBids[0].setAge(AgeRange.EighteenToTwentyFive);
            ageTargetBids[0].setIncrementalBid(IncrementalBidPercentage.EightyPercent);
            ageTargetBids[1] = new AgeTargetBid();
            ageTargetBids[1].setAge(AgeRange.TwentyFiveToThirtyFive);
            ageTargetBids[1].setIncrementalBid(IncrementalBidPercentage.FiftyPercent);
            AgeTarget ageTarget = new AgeTarget();
            ageTarget.setBids(ageTargetBids);

            // Bid incrementally on Friday and Saturday.
            DayTargetBid[] dayTargetBids = new DayTargetBid[2];
            dayTargetBids[0] = new DayTargetBid();
            dayTargetBids[0].setDay(Day.Friday);
            dayTargetBids[0].setIncrementalBid(IncrementalBidPercentage.TwentyPercent);
            dayTargetBids[1] = new DayTargetBid();
            dayTargetBids[1].setDay(Day.Saturday);
            dayTargetBids[1].setIncrementalBid(IncrementalBidPercentage.ThirtyPercent);
            DayTarget dayTarget = new DayTarget();
            dayTarget.setBids(dayTargetBids);
            dayTarget.setTargetAllDays(true);
            
            // Bid incrementally on gender.
            GenderTargetBid[] genderTargetBids = new GenderTargetBid[2];
            genderTargetBids[0] = new GenderTargetBid();
            genderTargetBids[0].setGender(GenderType.Male);
            genderTargetBids[0].setIncrementalBid(IncrementalBidPercentage.TenPercent);
            genderTargetBids[1] = new GenderTargetBid();
            genderTargetBids[1].setGender(GenderType.Female);
            genderTargetBids[1].setIncrementalBid(IncrementalBidPercentage.ThirtyPercent);
            GenderTarget genderTarget = new GenderTarget();
            genderTarget.setBids(genderTargetBids);

            // Bid incrementally on several hour ranges.
            HourTargetBid[] hourTargetBids = new HourTargetBid[3];
            hourTargetBids[0] = new HourTargetBid();
            hourTargetBids[0].setHour(HourRange.TwoPMToSixPM);
            hourTargetBids[0].setIncrementalBid(IncrementalBidPercentage.FortyPercent);
            hourTargetBids[1] = new HourTargetBid();
            hourTargetBids[1].setHour(HourRange.SixPMToElevenPM);
            hourTargetBids[1].setIncrementalBid(IncrementalBidPercentage.TwentyPercent);
            hourTargetBids[2] = new HourTargetBid();
            hourTargetBids[2].setHour(HourRange.ElevenPMToThreeAM);
            hourTargetBids[2].setIncrementalBid(IncrementalBidPercentage.TenPercent);
            HourTarget hourTarget = new HourTarget();
            hourTarget.setBids(hourTargetBids);
            
            // Bid incrementally on a state.
            StateTargetBid[] stateTargetBids = new StateTargetBid[1];
            stateTargetBids[0] = new StateTargetBid();
            stateTargetBids[0].setState("US-CA");  // This bid targets California.
            stateTargetBids[0].setIncrementalBid(IncrementalBidPercentage.NinetyPercent);
            StateTarget stateTarget = new StateTarget();
            stateTarget.setBids(stateTargetBids);

            LocationTarget locationTarget = new LocationTarget();
            locationTarget.setTargetAllLocations(true);
            locationTarget.setStateTarget(stateTarget);
            
            targets[0].setName("My Java Target #1");
            targets[0].setAge(ageTarget);
            targets[0].setDay(dayTarget);
            targets[0].setGender(genderTarget);
            targets[0].setHour(hourTarget);
            targets[0].setLocation(locationTarget);
           
            // Create the service operation request object, and assign values.
            addTargetsToLibraryRequest = new AddTargetsToLibraryRequest();
            addTargetsToLibraryRequest.setTargets(targets);
            
            // Make the call to add the targets.
            System.out.println(
                "Calling CampaignManagement.AddTargetsToLibrary");
            addTargetsToLibraryResponse = 
                campaignManagement.addTargetsToLibrary(addTargetsToLibraryRequest);
            
            // Display the TrackingId that was returned 
            // in the response header.
            System.out.println("Successful AddTargetsToLibrary call.");
            System.out.println(
                "TrackingId output from response header:");
            System.out.println(
             stub.getResponseHeader
             (
               namespace,
               "TrackingId")
             );

            // Insert a blank line to separate the text that follows.
            System.out.println();  

            // Display the target IDs for the targets that were created.
            for (int i = 0; i < addTargetsToLibraryResponse.getTargetIds().length; i++)
            {
                System.out.print(
                  String.format("Target named %s ",
                  targets[i].getName()));
                System.out.print("was created with ");
                System.out.println(
                     String.format("target ID %s.",
                     addTargetsToLibraryResponse.getTargetIds()[i]));
            }

        }

        // Exception handling.
        
        catch (ApiFaultDetail fault)
        {
            System.out.println("ApiFaultDetail exception encountered.");
            System.out.println(String.format("Tracking ID: %s",
                      fault.getTrackingId()));

            // Display service operation error information.
            for (int i = 0; i < fault.getOperationErrors().length; i++)
            {
                System.out.println("Operation error encountered:");
                System.out.println(String.format("\tMessage: %s",
                        fault.getOperationErrors()[i].getMessage()));
                System.out.println(String.format("\tDetails: %s",
                        fault.getOperationErrors()[i].getDetails()));
                System.out.println(String.format("\tErrorCode: %s",
                        fault.getOperationErrors()[i].getErrorCode()));
                System.out.println(String.format("\tCode: %s",
                        fault.getOperationErrors()[i].getCode()));
            }

            // Display batch error information.
            for (int i = 0; i < fault.getBatchErrors().length; i++)
            {
                System.out.println(String.format("Batch error encountered for array index %s.",
                        fault.getBatchErrors()[i].getIndex()));
                System.out.println(String.format("\tMessage: %s",
                        fault.getBatchErrors()[i].getMessage()));
                System.out.println(String.format("\tDetails: %s",
                        fault.getBatchErrors()[i].getDetails()));
                System.out.println(String.format("\tErrorCode: %s",
                        fault.getBatchErrors()[i].getErrorCode()));
                System.out.println(String.format("\tCode: %s",
                        fault.getBatchErrors()[i].getCode()));
            }

            // Exit the application or take other action.
            System.exit(-1);
        }
        
        catch (AdApiFaultDetail fault)
        {
            System.out.println("AdApiFaultDetail exception encountered.");
            System.out.println(String.format("Tracking ID: %s",
                      fault.getTrackingId()));

            // Display API error information.
            for (int i = 0; i < fault.getErrors().length; i++)
            {
                System.out.println("Error encountered:");
                System.out.println(String.format("\tMessage: %s",
                        fault.getErrors()[i].getMessage()));
                System.out.println(String.format("\tDetail: %s",
                        fault.getErrors()[i].getDetail()));
                System.out.println(String.format("\tErrorCode: %s",
                        fault.getErrors()[i].getErrorCode()));
                System.out.println(String.format("\tCode: %s",
                        fault.getErrors()[i].getCode()));
            }

            // Exit the application or take other action.
            System.exit(-1);
        }

        // Capture exceptions on the client that are unrelated to
        // the Bing Ads API.
        catch (Exception e)
        {
            System.out.print("Error encountered: ");
            e.printStackTrace();
            
            // Exit the application or take other action.
            System.exit(-1);
        }

    }
}

Community Additions

Show:
© 2015 Microsoft