The code samples below provide examples of common targeting functions using the AdWords API. Client Library.
Add targeting criteria to a campaign
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201809.targeting; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import com.beust.jcommander.Parameter; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.v201809.cm.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterion; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterionOperation; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterionReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterionServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.ConstantOperand; import com.google.api.ads.adwords.axis.v201809.cm.ConstantOperandConstantType; import com.google.api.ads.adwords.axis.v201809.cm.ConstantOperandUnit; import com.google.api.ads.adwords.axis.v201809.cm.Criterion; import com.google.api.ads.adwords.axis.v201809.cm.Function; import com.google.api.ads.adwords.axis.v201809.cm.FunctionArgumentOperand; import com.google.api.ads.adwords.axis.v201809.cm.FunctionOperator; import com.google.api.ads.adwords.axis.v201809.cm.Keyword; import com.google.api.ads.adwords.axis.v201809.cm.KeywordMatchType; import com.google.api.ads.adwords.axis.v201809.cm.Language; import com.google.api.ads.adwords.axis.v201809.cm.Location; import com.google.api.ads.adwords.axis.v201809.cm.LocationExtensionOperand; import com.google.api.ads.adwords.axis.v201809.cm.LocationGroups; import com.google.api.ads.adwords.axis.v201809.cm.NegativeCampaignCriterion; import com.google.api.ads.adwords.axis.v201809.cm.Operator; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface; import com.google.api.ads.adwords.lib.utils.examples.ArgumentNames; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.conf.ConfigurationLoadException; import com.google.api.ads.common.lib.exception.OAuthException; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.common.lib.utils.examples.CodeSampleParams; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * This example adds various types of targeting criteria to a campaign. To get * campaigns, run GetCampaigns.java * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class AddCampaignTargetingCriteria { private static class AddCampaignTargetingCriteriaParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private Long campaignId; @Parameter(names = ArgumentNames.LOCATION_FEED_ID, description = "The ID of a feed that has been configured for location targeting, meaning it" + " has an ENABLED FeedMapping with criterionType of 77. Feeds linked to a GMB account" + " automatically have this FeedMapping. If you don't have such a feed, this argument" + " is unnecessary.") private Long locationFeedId; } public static void main(String[] args) { AdWordsSession session; try { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build(); } catch (ConfigurationLoadException cle) { System.err.printf( "Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle); return; } catch (ValidationException ve) { System.err.printf( "Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve); return; } catch (OAuthException oe) { System.err.printf( "Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe); return; } AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance(); AddCampaignTargetingCriteriaParams params = new AddCampaignTargetingCriteriaParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE"); params.locationFeedId = Long.parseLong("INSERT_LOCATION_FEED_ID_HERE"); } try { runExample(adWordsServices, session, params.campaignId, params.locationFeedId); } catch (ApiException apiException) { // ApiException is the base class for most exceptions thrown by an API request. Instances // of this exception have a message and a collection of ApiErrors that indicate the // type and underlying cause of the exception. Every exception object in the adwords.axis // packages will return a meaningful value from toString // // ApiException extends RemoteException, so this catch block must appear before the // catch block for RemoteException. System.err.println("Request failed due to ApiException. Underlying ApiErrors:"); if (apiException.getErrors() != null) { int i = 0; for (ApiError apiError : apiException.getErrors()) { System.err.printf(" Error %d: %s%n", i++, apiError); } } } catch (RemoteException re) { System.err.printf( "Request failed unexpectedly due to RemoteException: %s%n", re); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @param campaignId the ID of the campaign where targeting criteria will be added. * @param locationFeedId optional ID of a location targeting feed. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. */ public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId, @Nullable Long locationFeedId) throws RemoteException { // Get the CampaignService. CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session, CampaignCriterionServiceInterface.class); // Create locations. The IDs can be found in the documentation or // retrieved with the LocationCriterionService. Location california = new Location(); california.setId(21137L); Location mexico = new Location(); mexico.setId(2484L); // Create languages. The IDs can be found in the documentation or // retrieved with the ConstantDataService. Language english = new Language(); english.setId(1000L); Language spanish = new Language(); spanish.setId(1003L); List<Criterion> criteria = new ArrayList<>(Arrays.asList(california, mexico, english, spanish)); // Distance targeting. Area of 10 miles around the locations in the location feed. if (locationFeedId != null) { LocationGroups radiusLocationGroup = new LocationGroups(); radiusLocationGroup.setFeedId(locationFeedId); ConstantOperand radius = new ConstantOperand(); radius.setType(ConstantOperandConstantType.DOUBLE); radius.setUnit(ConstantOperandUnit.MILES); radius.setDoubleValue(10d); LocationExtensionOperand distance = new LocationExtensionOperand(); distance.setRadius(radius); Function radiusMatchingFunction = new Function(); radiusMatchingFunction.setOperator(FunctionOperator.IDENTITY); radiusMatchingFunction.setLhsOperand(new FunctionArgumentOperand[] {distance}); radiusLocationGroup.setMatchingFunction(radiusMatchingFunction); criteria.add(radiusLocationGroup); } // Create operations to add each of the criteria above. List<CampaignCriterionOperation> operations = new ArrayList<>(); for (Criterion criterion : criteria) { CampaignCriterionOperation operation = new CampaignCriterionOperation(); CampaignCriterion campaignCriterion = new CampaignCriterion(); campaignCriterion.setCampaignId(campaignId); campaignCriterion.setCriterion(criterion); operation.setOperand(campaignCriterion); operation.setOperator(Operator.ADD); operations.add(operation); } // Add a negative campaign criterion. Keyword negativeKeyword = new Keyword(); negativeKeyword.setText("jupiter cruise"); negativeKeyword.setMatchType(KeywordMatchType.BROAD); CampaignCriterion negativeCriterion = new NegativeCampaignCriterion(); negativeCriterion.setCampaignId(campaignId); negativeCriterion.setCriterion(negativeKeyword); CampaignCriterionOperation operation = new CampaignCriterionOperation(); operation.setOperand(negativeCriterion); operation.setOperator(Operator.ADD); operations.add(operation); CampaignCriterionReturnValue result = campaignCriterionService.mutate(operations .toArray(new CampaignCriterionOperation[operations.size()])); // Display campaigns. for (CampaignCriterion campaignCriterion : result.getValue()) { System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, " + "and type '%s' was added.%n", campaignCriterion.getCampaignId(), campaignCriterion .getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType()); } } }
Add negative criteria to a customer
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201809.targeting; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.v201809.cm.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.ContentLabel; import com.google.api.ads.adwords.axis.v201809.cm.ContentLabelType; import com.google.api.ads.adwords.axis.v201809.cm.Criterion; import com.google.api.ads.adwords.axis.v201809.cm.CustomerNegativeCriterion; import com.google.api.ads.adwords.axis.v201809.cm.CustomerNegativeCriterionOperation; import com.google.api.ads.adwords.axis.v201809.cm.CustomerNegativeCriterionReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.CustomerNegativeCriterionServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.Operator; import com.google.api.ads.adwords.axis.v201809.cm.Placement; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.conf.ConfigurationLoadException; import com.google.api.ads.common.lib.exception.OAuthException; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; /** * This example adds various types of negative criteria to a customer. These criteria will be * applied to all campaigns for the customer. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class AddCustomerNegativeCriteria { public static void main(String[] args) { AdWordsSession session; try { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build(); } catch (ConfigurationLoadException cle) { System.err.printf( "Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle); return; } catch (ValidationException ve) { System.err.printf( "Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve); return; } catch (OAuthException oe) { System.err.printf( "Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe); return; } AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance(); try { runExample(adWordsServices, session); } catch (ApiException apiException) { // ApiException is the base class for most exceptions thrown by an API request. Instances // of this exception have a message and a collection of ApiErrors that indicate the // type and underlying cause of the exception. Every exception object in the adwords.axis // packages will return a meaningful value from toString // // ApiException extends RemoteException, so this catch block must appear before the // catch block for RemoteException. System.err.println("Request failed due to ApiException. Underlying ApiErrors:"); if (apiException.getErrors() != null) { int i = 0; for (ApiError apiError : apiException.getErrors()) { System.err.printf(" Error %d: %s%n", i++, apiError); } } } catch (RemoteException re) { System.err.printf( "Request failed unexpectedly due to RemoteException: %s%n", re); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. */ public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException { // Get the CustomerNegativeCriterionService. CustomerNegativeCriterionServiceInterface customerNegativeCriterionService = adWordsServices.get(session, CustomerNegativeCriterionServiceInterface.class); List<Criterion> criteria = new ArrayList<>(); // Exclude tragedy & conflict content. ContentLabel tragedyContentLabel = new ContentLabel(); tragedyContentLabel.setContentLabelType(ContentLabelType.TRAGEDY); criteria.add(tragedyContentLabel); // Exclude a specific placement. Placement placement = new Placement(); placement.setUrl("http://www.example.com"); criteria.add(placement); // Additional criteria types are available for this service. See the types listed // under Criterion here: // https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion // Create operations to add each of the criteria above. List<CustomerNegativeCriterionOperation> operations = new ArrayList<>(); for (Criterion criterion : criteria) { CustomerNegativeCriterion negativeCriterion = new CustomerNegativeCriterion(); negativeCriterion.setCriterion(criterion); CustomerNegativeCriterionOperation operation = new CustomerNegativeCriterionOperation(); operation.setOperator(Operator.ADD); operation.setOperand(negativeCriterion); operations.add(operation); } // Send the request to add the criteria. CustomerNegativeCriterionReturnValue result = customerNegativeCriterionService.mutate( operations.toArray(new CustomerNegativeCriterionOperation[operations.size()])); // Display the results. for (CustomerNegativeCriterion negativeCriterion : result.getValue()) { System.out.printf( "Customer negative criterion with criterion ID %d and type '%s' was added.%n", negativeCriterion.getCriterion().getId(), negativeCriterion.getCriterion().getCriterionType()); } } }
Add demographic critera to an ad group
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201809.targeting; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import com.beust.jcommander.Parameter; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterion; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AgeRange; import com.google.api.ads.adwords.axis.v201809.cm.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion; import com.google.api.ads.adwords.axis.v201809.cm.Gender; import com.google.api.ads.adwords.axis.v201809.cm.NegativeAdGroupCriterion; import com.google.api.ads.adwords.axis.v201809.cm.Operator; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface; import com.google.api.ads.adwords.lib.utils.examples.ArgumentNames; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.conf.ConfigurationLoadException; import com.google.api.ads.common.lib.exception.OAuthException; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.common.lib.utils.examples.CodeSampleParams; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; /** * This example adds demographic criteria to an ad group. To get ad groups, run * GetAdGroups.java * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class AddDemographicTargetingCriteria { private static class AddDemographicTargetingCriteriaParams extends CodeSampleParams { @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true) private Long adGroupId; } public static void main(String[] args) { AdWordsSession session; try { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build(); } catch (ConfigurationLoadException cle) { System.err.printf( "Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle); return; } catch (ValidationException ve) { System.err.printf( "Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve); return; } catch (OAuthException oe) { System.err.printf( "Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe); return; } AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance(); AddDemographicTargetingCriteriaParams params = new AddDemographicTargetingCriteriaParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE"); } try { runExample(adWordsServices, session, params.adGroupId); } catch (ApiException apiException) { // ApiException is the base class for most exceptions thrown by an API request. Instances // of this exception have a message and a collection of ApiErrors that indicate the // type and underlying cause of the exception. Every exception object in the adwords.axis // packages will return a meaningful value from toString // // ApiException extends RemoteException, so this catch block must appear before the // catch block for RemoteException. System.err.println("Request failed due to ApiException. Underlying ApiErrors:"); if (apiException.getErrors() != null) { int i = 0; for (ApiError apiError : apiException.getErrors()) { System.err.printf(" Error %d: %s%n", i++, apiError); } } } catch (RemoteException re) { System.err.printf( "Request failed unexpectedly due to RemoteException: %s%n", re); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @param adGroupId the ID of the ad group where demographic targeting will be modified. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. */ public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId) throws RemoteException { // Get the AdGroupCriterionService. AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class); // https://developers.google.com/adwords/api/docs/appendix/genders Gender male = new Gender(); male.setId(10L); BiddableAdGroupCriterion genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion(); genderBiddableAdGroupCriterion.setAdGroupId(adGroupId); genderBiddableAdGroupCriterion.setCriterion(male); // https://developers.google.com/adwords/api/docs/appendix/ages AgeRange undetermined = new AgeRange(); undetermined.setId(503999L); NegativeAdGroupCriterion ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion(); ageRangeNegativeAdGroupCriterion.setAdGroupId(adGroupId); ageRangeNegativeAdGroupCriterion.setCriterion(undetermined); AdGroupCriterionOperation genderAdGroupCriterionOperation = new AdGroupCriterionOperation(); genderAdGroupCriterionOperation.setOperand(genderBiddableAdGroupCriterion); genderAdGroupCriterionOperation.setOperator(Operator.ADD); AdGroupCriterionOperation ageRangeNegativeAdGroupCriterionOperation = new AdGroupCriterionOperation(); ageRangeNegativeAdGroupCriterionOperation.setOperand(ageRangeNegativeAdGroupCriterion); ageRangeNegativeAdGroupCriterionOperation.setOperator(Operator.ADD); AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { genderAdGroupCriterionOperation, ageRangeNegativeAdGroupCriterionOperation}); // Display campaigns. for (AdGroupCriterion adGroupCriterion : result.getValue()) { System.out.printf("AdGroup criterion with adGroup ID %d, criterion ID %d, " + "and type '%s' was added.%n", adGroupCriterion.getAdGroupId(), adGroupCriterion.getCriterion().getId(), adGroupCriterion.getCriterion().getCriterionType()); } } }
Get all campaign criteria
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201809.targeting; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder; import com.google.api.ads.adwords.axis.v201809.cm.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterion; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterionPage; import com.google.api.ads.adwords.axis.v201809.cm.CampaignCriterionServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.Selector; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface; import com.google.api.ads.adwords.lib.selectorfields.v201809.cm.CampaignCriterionField; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.conf.ConfigurationLoadException; import com.google.api.ads.common.lib.exception.OAuthException; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; /** * This example illustrates how to retrieve all the campaign criteria. To add * campaign criteria, run AddCampaignTargetingCriteria.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class GetCampaignTargetingCriteria { private static final int PAGE_SIZE = 100; public static void main(String[] args) { AdWordsSession session; try { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build(); } catch (ConfigurationLoadException cle) { System.err.printf( "Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle); return; } catch (ValidationException ve) { System.err.printf( "Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve); return; } catch (OAuthException oe) { System.err.printf( "Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe); return; } AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance(); try { runExample(adWordsServices, session); } catch (ApiException apiException) { // ApiException is the base class for most exceptions thrown by an API request. Instances // of this exception have a message and a collection of ApiErrors that indicate the // type and underlying cause of the exception. Every exception object in the adwords.axis // packages will return a meaningful value from toString // // ApiException extends RemoteException, so this catch block must appear before the // catch block for RemoteException. System.err.println("Request failed due to ApiException. Underlying ApiErrors:"); if (apiException.getErrors() != null) { int i = 0; for (ApiError apiError : apiException.getErrors()) { System.err.printf(" Error %d: %s%n", i++, apiError); } } } catch (RemoteException re) { System.err.printf( "Request failed unexpectedly due to RemoteException: %s%n", re); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. */ public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException { // Get the CampaignService. CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session, CampaignCriterionServiceInterface.class); int offset = 0; // Create selector. SelectorBuilder builder = new SelectorBuilder(); Selector selector = builder .fields( CampaignCriterionField.CampaignId, CampaignCriterionField.Id, CampaignCriterionField.CriteriaType, CampaignCriterionField.PlatformName, CampaignCriterionField.LanguageName, CampaignCriterionField.LocationName, CampaignCriterionField.KeywordText) .in(CampaignCriterionField.CriteriaType, "KEYWORD", "LANGUAGE", "LOCATION", "PLATFORM") .offset(0) .limit(PAGE_SIZE) .build(); CampaignCriterionPage page = null; do { page = campaignCriterionService.get(selector); if (page.getEntries() != null) { // Display campaigns. for (CampaignCriterion campaignCriterion : page.getEntries()) { System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, " + "and type '%s' was found.%n", campaignCriterion.getCampaignId(), campaignCriterion .getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType()); } } else { System.out.println("No campaign criteria were found."); } offset += PAGE_SIZE; selector = builder.increaseOffsetBy(PAGE_SIZE).build(); } while (offset < page.getTotalNumEntries()); } }
Get all targetable languages and carriers
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201809.targeting; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.v201809.cm.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.Carrier; import com.google.api.ads.adwords.axis.v201809.cm.ConstantDataServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.Language; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.conf.ConfigurationLoadException; import com.google.api.ads.common.lib.exception.OAuthException; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; /** * This example illustrates how to retrieve all languages and carriers available * for targeting. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class GetTargetableLanguagesAndCarriers { public static void main(String[] args) { AdWordsSession session; try { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build(); } catch (ConfigurationLoadException cle) { System.err.printf( "Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle); return; } catch (ValidationException ve) { System.err.printf( "Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve); return; } catch (OAuthException oe) { System.err.printf( "Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe); return; } AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance(); try { runExample(adWordsServices, session); } catch (ApiException apiException) { // ApiException is the base class for most exceptions thrown by an API request. Instances // of this exception have a message and a collection of ApiErrors that indicate the // type and underlying cause of the exception. Every exception object in the adwords.axis // packages will return a meaningful value from toString // // ApiException extends RemoteException, so this catch block must appear before the // catch block for RemoteException. System.err.println("Request failed due to ApiException. Underlying ApiErrors:"); if (apiException.getErrors() != null) { int i = 0; for (ApiError apiError : apiException.getErrors()) { System.err.printf(" Error %d: %s%n", i++, apiError); } } } catch (RemoteException re) { System.err.printf( "Request failed unexpectedly due to RemoteException: %s%n", re); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. */ public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException { // Get the ConstantDataService. ConstantDataServiceInterface constantDataService = adWordsServices.get(session, ConstantDataServiceInterface.class); // Get all carriers. Carrier[] carriers = constantDataService.getCarrierCriterion(); // Display results. for (Carrier carrier : carriers) { System.out.printf("Carrier with name '%s', ID %d, and country code '%s' was found.%n", carrier.getName(), carrier.getId(), carrier.getCountryCode()); } // Get all languages. Language[] languages = constantDataService.getLanguageCriterion(); // Display results. for (Language language : languages) { System.out.printf("Language with name '%s' and ID %d was found.%n", language.getName(), language.getId()); } } }
Get location criteria by name
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201809.targeting; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder; import com.google.api.ads.adwords.axis.v201809.cm.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.Location; import com.google.api.ads.adwords.axis.v201809.cm.LocationCriterion; import com.google.api.ads.adwords.axis.v201809.cm.LocationCriterionServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.Selector; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.conf.ConfigurationLoadException; import com.google.api.ads.common.lib.exception.OAuthException; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; /** * This example gets location criteria by name. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class LookupLocation { /** * Helper function to format a string for parent locations. * * @param parents List of parent locations. * @return Formatted string representing parent locations. */ public static String getParentLocationString(Location[] parents) { StringBuilder sb = new StringBuilder(); if (parents != null) { for (Location parent : parents) { if (sb.length() > 0) { sb.append(", "); } sb.append(String.format("%s (%s)", parent.getLocationName(), parent.getDisplayType())); } } else { sb.append("N/A"); } return sb.toString(); } public static void main(String[] args) { AdWordsSession session; try { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build(); } catch (ConfigurationLoadException cle) { System.err.printf( "Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle); return; } catch (ValidationException ve) { System.err.printf( "Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve); return; } catch (OAuthException oe) { System.err.printf( "Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe); return; } AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance(); String[] locationNames = new String[] {"Paris", "Quebec", "Spain", "Deutschland"}; try { runExample(adWordsServices, session, locationNames); } catch (ApiException apiException) { // ApiException is the base class for most exceptions thrown by an API request. Instances // of this exception have a message and a collection of ApiErrors that indicate the // type and underlying cause of the exception. Every exception object in the adwords.axis // packages will return a meaningful value from toString // // ApiException extends RemoteException, so this catch block must appear before the // catch block for RemoteException. System.err.println("Request failed due to ApiException. Underlying ApiErrors:"); if (apiException.getErrors() != null) { int i = 0; for (ApiError apiError : apiException.getErrors()) { System.err.printf(" Error %d: %s%n", i++, apiError); } } } catch (RemoteException re) { System.err.printf( "Request failed unexpectedly due to RemoteException: %s%n", re); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @param locationNames the location names to use for the lookup. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. */ public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session, String[] locationNames) throws RemoteException { // Get the LocationCriterionService. LocationCriterionServiceInterface locationCriterionService = adWordsServices.get(session, LocationCriterionServiceInterface.class); Selector selector = new SelectorBuilder() .fields( "Id", "LocationName", "CanonicalName", "DisplayType", "ParentLocations", "Reach", "TargetingStatus") // Location names must match exactly, only EQUALS and IN are supported. .in("LocationName", locationNames) // Set the locale of the returned location names. .equals("Locale", "en") .build(); // Make the get request. LocationCriterion[] locationCriteria = locationCriterionService.get(selector); // Display the resulting location criteria. for (LocationCriterion locationCriterion : locationCriteria) { String parentString = getParentLocationString(locationCriterion.getLocation().getParentLocations()); System.out.printf("The search term '%s' returned the location '%s (%d)' of type '%s' " + "with parent locations '%s' and reach %d (%s).%n", locationCriterion.getSearchTerm(), locationCriterion.getLocation().getLocationName(), locationCriterion.getLocation() .getId(), locationCriterion.getLocation().getDisplayType(), parentString, locationCriterion.getReach(), locationCriterion.getLocation().getTargetingStatus()); } } }