The code samples below provide examples of basic operations using the AdWords API. Client Library.
Add ad groups 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.basicoperations; 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.AdGroup; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdRotationMode; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupStatus; import com.google.api.ads.adwords.axis.v201809.cm.AdRotationMode; 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.BiddingStrategyConfiguration; import com.google.api.ads.adwords.axis.v201809.cm.Bids; import com.google.api.ads.adwords.axis.v201809.cm.CpcBid; import com.google.api.ads.adwords.axis.v201809.cm.CriterionTypeGroup; import com.google.api.ads.adwords.axis.v201809.cm.Money; import com.google.api.ads.adwords.axis.v201809.cm.Operator; import com.google.api.ads.adwords.axis.v201809.cm.Setting; import com.google.api.ads.adwords.axis.v201809.cm.TargetingSetting; import com.google.api.ads.adwords.axis.v201809.cm.TargetingSettingDetail; 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 ad groups 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 AddAdGroups { private static class AddAdGroupsParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private Long campaignId; } 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(); AddAdGroupsParams params = new AddAdGroupsParams(); 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"); } try { runExample(adWordsServices, session, params.campaignId); } 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 the ad groups will be created. * @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) throws RemoteException { // Get the AdGroupService. AdGroupServiceInterface adGroupService = adWordsServices.get(session, AdGroupServiceInterface.class); // Create ad group. AdGroup adGroup = new AdGroup(); adGroup.setName("Earth to Mars Cruises #" + System.currentTimeMillis()); adGroup.setStatus(AdGroupStatus.ENABLED); adGroup.setCampaignId(campaignId); // Optional settings. // Targeting restriction settings. Depending on the criterionTypeGroup // value, most TargetingSettingDetail only affect Display campaigns. // However, the USER_INTEREST_AND_LIST value works for RLSA campaigns - // Search campaigns targeting using a remarketing list. TargetingSetting targeting = new TargetingSetting(); // Restricting to serve ads that match your ad group placements. // This is equivalent to choosing "Target and bid" in the UI. TargetingSettingDetail placements = new TargetingSettingDetail(); placements.setCriterionTypeGroup(CriterionTypeGroup.PLACEMENT); placements.setTargetAll(Boolean.FALSE); // Using your ad group verticals only for bidding. This is equivalent // to choosing "Bid only" in the UI. TargetingSettingDetail verticals = new TargetingSettingDetail(); verticals.setCriterionTypeGroup(CriterionTypeGroup.VERTICAL); verticals.setTargetAll(Boolean.TRUE); targeting.setDetails(new TargetingSettingDetail[] {placements, verticals}); adGroup.setSettings(new Setting[] {targeting}); // Set the rotation mode. AdGroupAdRotationMode rotationMode = new AdGroupAdRotationMode(AdRotationMode.OPTIMIZE); adGroup.setAdGroupAdRotationMode(rotationMode); // Create ad group bid. BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); Money cpcBidMoney = new Money(); cpcBidMoney.setMicroAmount(10_000_000L); CpcBid bid = new CpcBid(); bid.setBid(cpcBidMoney); biddingStrategyConfiguration.setBids(new Bids[] {bid}); adGroup.setBiddingStrategyConfiguration(biddingStrategyConfiguration); // Add as many additional ad groups as you need. AdGroup adGroup2 = new AdGroup(); adGroup2.setName("Earth to Venus Cruises #" + System.currentTimeMillis()); adGroup2.setStatus(AdGroupStatus.ENABLED); adGroup2.setCampaignId(campaignId); BiddingStrategyConfiguration biddingStrategyConfiguration2 = new BiddingStrategyConfiguration(); Money cpcBidMoney2 = new Money(); cpcBidMoney2.setMicroAmount(10_000_000L); CpcBid bid2 = new CpcBid(); bid2.setBid(cpcBidMoney2); biddingStrategyConfiguration2.setBids(new Bids[] {bid2}); adGroup2.setBiddingStrategyConfiguration(biddingStrategyConfiguration2); // Create operations. AdGroupOperation operation = new AdGroupOperation(); operation.setOperand(adGroup); operation.setOperator(Operator.ADD); AdGroupOperation operation2 = new AdGroupOperation(); operation2.setOperand(adGroup2); operation2.setOperator(Operator.ADD); AdGroupOperation[] operations = new AdGroupOperation[] {operation, operation2}; // Add ad groups. AdGroupReturnValue result = adGroupService.mutate(operations); // Display new ad groups. for (AdGroup adGroupResult : result.getValue()) { System.out.printf("Ad group with name '%s' and ID %d was added.%n", adGroupResult.getName(), adGroupResult.getId()); } } }
Add campaigns
// 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.basicoperations; 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.AdvertisingChannelType; 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.BiddingStrategyConfiguration; import com.google.api.ads.adwords.axis.v201809.cm.BiddingStrategyType; import com.google.api.ads.adwords.axis.v201809.cm.Budget; import com.google.api.ads.adwords.axis.v201809.cm.BudgetBudgetDeliveryMethod; import com.google.api.ads.adwords.axis.v201809.cm.BudgetOperation; import com.google.api.ads.adwords.axis.v201809.cm.BudgetServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.Campaign; import com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation; import com.google.api.ads.adwords.axis.v201809.cm.CampaignReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.CampaignStatus; import com.google.api.ads.adwords.axis.v201809.cm.FrequencyCap; import com.google.api.ads.adwords.axis.v201809.cm.GeoTargetTypeSetting; import com.google.api.ads.adwords.axis.v201809.cm.GeoTargetTypeSettingPositiveGeoTargetType; import com.google.api.ads.adwords.axis.v201809.cm.Level; import com.google.api.ads.adwords.axis.v201809.cm.ManualCpcBiddingScheme; import com.google.api.ads.adwords.axis.v201809.cm.Money; import com.google.api.ads.adwords.axis.v201809.cm.NetworkSetting; import com.google.api.ads.adwords.axis.v201809.cm.Operator; import com.google.api.ads.adwords.axis.v201809.cm.Setting; import com.google.api.ads.adwords.axis.v201809.cm.TimeUnit; 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 org.joda.time.DateTime; /** * This example adds campaigns. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class AddCampaigns { 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 BudgetService. BudgetServiceInterface budgetService = adWordsServices.get(session, BudgetServiceInterface.class); // Create a budget, which can be shared by multiple campaigns. Budget sharedBudget = new Budget(); sharedBudget.setName("Interplanetary Cruise #" + System.currentTimeMillis()); Money budgetAmount = new Money(); budgetAmount.setMicroAmount(50_000_000L); sharedBudget.setAmount(budgetAmount); sharedBudget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD); BudgetOperation budgetOperation = new BudgetOperation(); budgetOperation.setOperand(sharedBudget); budgetOperation.setOperator(Operator.ADD); // Add the budget Long budgetId = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0).getBudgetId(); // Get the CampaignService. CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class); // Create campaign. Campaign campaign = new Campaign(); campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis()); // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. campaign.setStatus(CampaignStatus.PAUSED); BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC); // You can optionally provide a bidding scheme in place of the type. ManualCpcBiddingScheme cpcBiddingScheme = new ManualCpcBiddingScheme(); biddingStrategyConfiguration.setBiddingScheme(cpcBiddingScheme); campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration); // You can optionally provide these field(s). campaign.setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd")); campaign.setEndDate(new DateTime().plusDays(30).toString("yyyyMMdd")); campaign.setFrequencyCap(new FrequencyCap(5L, TimeUnit.DAY, Level.ADGROUP)); // Only the budgetId should be sent, all other fields will be ignored by CampaignService. Budget budget = new Budget(); budget.setBudgetId(budgetId); campaign.setBudget(budget); campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH); // Set the campaign network options to Search and Search Network. NetworkSetting networkSetting = new NetworkSetting(); networkSetting.setTargetGoogleSearch(true); networkSetting.setTargetSearchNetwork(true); networkSetting.setTargetContentNetwork(false); networkSetting.setTargetPartnerSearchNetwork(false); campaign.setNetworkSetting(networkSetting); // Set options that are not required. GeoTargetTypeSetting geoTarget = new GeoTargetTypeSetting(); geoTarget.setPositiveGeoTargetType(GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE); campaign.setSettings(new Setting[] {geoTarget}); // You can create multiple campaigns in a single request. Campaign campaign2 = new Campaign(); campaign2.setName("Interplanetary Cruise banner #" + System.currentTimeMillis()); campaign2.setStatus(CampaignStatus.PAUSED); BiddingStrategyConfiguration biddingStrategyConfiguration2 = new BiddingStrategyConfiguration(); biddingStrategyConfiguration2.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC); campaign2.setBiddingStrategyConfiguration(biddingStrategyConfiguration2); Budget budget2 = new Budget(); budget2.setBudgetId(budgetId); campaign2.setBudget(budget2); campaign2.setAdvertisingChannelType(AdvertisingChannelType.DISPLAY); // Create operations. CampaignOperation operation = new CampaignOperation(); operation.setOperand(campaign); operation.setOperator(Operator.ADD); CampaignOperation operation2 = new CampaignOperation(); operation2.setOperand(campaign2); operation2.setOperator(Operator.ADD); CampaignOperation[] operations = new CampaignOperation[] {operation, operation2}; // Add campaigns. CampaignReturnValue result = campaignService.mutate(operations); // Display campaigns. for (Campaign campaignResult : result.getValue()) { System.out.printf("Campaign with name '%s' and ID %d was added.%n", campaignResult.getName(), campaignResult.getId()); } } }
Add expanded text ads 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.basicoperations; 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.AdGroupAd; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdStatus; 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.ExpandedTextAd; 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; /** * This example adds several expanded text ads to a given 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 AddExpandedTextAds { private static final int NUMBER_OF_ADS = 5; private static class AddExpandedTextAdsParams 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(); AddExpandedTextAdsParams params = new AddExpandedTextAdsParams(); 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 the ad will be created. * @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 AdGroupAdService. AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class); List<AdGroupAdOperation> operations = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_ADS; i++) { // Create expanded text ad. ExpandedTextAd expandedTextAd = new ExpandedTextAd(); expandedTextAd.setHeadlinePart1(String.format("Cruise #%d to Mars", i)); expandedTextAd.setHeadlinePart2("Best Space Cruise Line"); expandedTextAd.setHeadlinePart3("For Your Loved Ones"); expandedTextAd.setDescription("Buy your tickets now!"); expandedTextAd.setDescription2("Discount ends soon"); expandedTextAd.setFinalUrls(new String[] {"http://www.example.com/" + i}); // Create ad group ad. AdGroupAd expandedTextAdGroupAd = new AdGroupAd(); expandedTextAdGroupAd.setAdGroupId(adGroupId); expandedTextAdGroupAd.setAd(expandedTextAd); // Optional: set the status. expandedTextAdGroupAd.setStatus(AdGroupAdStatus.PAUSED); // Create the operation. AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.setOperand(expandedTextAdGroupAd); adGroupAdOperation.setOperator(Operator.ADD); operations.add(adGroupAdOperation); } // Add ads. AdGroupAdReturnValue result = adGroupAdService.mutate(operations.toArray(new AdGroupAdOperation[operations.size()])); // Display ads. Arrays.stream(result.getValue()) .map(adGroupAdResult -> (ExpandedTextAd) adGroupAdResult.getAd()) .forEach( newAd -> System.out.printf( "Expanded text ad with ID %d and headline '%s | %s%s' was added.%n", newAd.getId(), newAd.getHeadlinePart1(), newAd.getHeadlinePart2(), newAd.getHeadlinePart3() == null ? "" : String.format(" | %s", newAd.getHeadlinePart3()))); } }
Add keywords 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.basicoperations; import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME; import static java.nio.charset.StandardCharsets.UTF_8; 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.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.BiddingStrategyConfiguration; import com.google.api.ads.adwords.axis.v201809.cm.Bids; import com.google.api.ads.adwords.axis.v201809.cm.CpcBid; 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.Money; 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.axis.v201809.cm.UrlList; import com.google.api.ads.adwords.axis.v201809.cm.UserStatus; 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.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.rmi.RemoteException; /** * This example adds keywords to an ad group. To get ad groups, run * AddAdGroup.java * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class AddKeywords { private static class AddKeywordsParams 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(); AddKeywordsParams params = new AddKeywordsParams(); 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); } catch (UnsupportedEncodingException ue) { System.err.printf("Example failed due to encoding exception: %s%n", ue); } } /** * Runs the example. * * @param adWordsServices the services factory. * @param session the session. * @param adGroupId the ID of the ad group where the keywords will be created. * @throws ApiException if the API request failed with one or more service errors. * @throws RemoteException if the API request failed due to other errors. * @throws UnsupportedEncodingException if encoding the final URL failed. */ public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session, long adGroupId) throws RemoteException, UnsupportedEncodingException { // Get the AdGroupCriterionService. AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class); // Create keywords. Keyword keyword1 = new Keyword(); keyword1.setText("mars cruise"); keyword1.setMatchType(KeywordMatchType.BROAD); Keyword keyword2 = new Keyword(); keyword2.setText("space hotel"); keyword2.setMatchType(KeywordMatchType.EXACT); // Create biddable ad group criterion. BiddableAdGroupCriterion keywordBiddableAdGroupCriterion1 = new BiddableAdGroupCriterion(); keywordBiddableAdGroupCriterion1.setAdGroupId(adGroupId); keywordBiddableAdGroupCriterion1.setCriterion(keyword1); // You can optionally provide these field(s). keywordBiddableAdGroupCriterion1.setUserStatus(UserStatus.PAUSED); String encodedFinalUrl = String.format("http://example.com/mars/cruise/?kw=%s", URLEncoder.encode(keyword1.getText(), UTF_8.name())); keywordBiddableAdGroupCriterion1.setFinalUrls(new UrlList(new String[] {encodedFinalUrl})); BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); CpcBid bid = new CpcBid(); bid.setBid(new Money(null, 10000000L)); biddingStrategyConfiguration.setBids(new Bids[] {bid}); keywordBiddableAdGroupCriterion1.setBiddingStrategyConfiguration(biddingStrategyConfiguration); NegativeAdGroupCriterion keywordNegativeAdGroupCriterion2 = new NegativeAdGroupCriterion(); keywordNegativeAdGroupCriterion2.setAdGroupId(adGroupId); keywordNegativeAdGroupCriterion2.setCriterion(keyword2); // Create operations. AdGroupCriterionOperation keywordAdGroupCriterionOperation1 = new AdGroupCriterionOperation(); keywordAdGroupCriterionOperation1.setOperand(keywordBiddableAdGroupCriterion1); keywordAdGroupCriterionOperation1.setOperator(Operator.ADD); AdGroupCriterionOperation keywordAdGroupCriterionOperation2 = new AdGroupCriterionOperation(); keywordAdGroupCriterionOperation2.setOperand(keywordNegativeAdGroupCriterion2); keywordAdGroupCriterionOperation2.setOperator(Operator.ADD); AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] {keywordAdGroupCriterionOperation1, keywordAdGroupCriterionOperation2}; // Add keywords. AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations); // Display results. for (AdGroupCriterion adGroupCriterionResult : result.getValue()) { System.out.printf("Keyword ad group criterion with ad group ID %d, criterion ID %d, " + "text '%s', and match type '%s' was added.%n", adGroupCriterionResult.getAdGroupId(), adGroupCriterionResult.getCriterion().getId(), ((Keyword) adGroupCriterionResult.getCriterion()).getText(), ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType()); } } }
Add a responsive search ad to an ad group
// Copyright 2018 Google LLC // // 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 // // https://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.basicoperations; 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.AdGroupAd; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdStatus; 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.AssetLink; import com.google.api.ads.adwords.axis.v201809.cm.Operator; import com.google.api.ads.adwords.axis.v201809.cm.ResponsiveSearchAd; import com.google.api.ads.adwords.axis.v201809.cm.ServedAssetFieldType; import com.google.api.ads.adwords.axis.v201809.cm.TextAsset; 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.List; /** * This example adds a responsive search ad to a given 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 AddResponsiveSearchAd { private static class AddResponsiveSearchAdParams 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(); AddResponsiveSearchAdParams params = new AddResponsiveSearchAdParams(); 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 the ad will be created. * @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 AdGroupAdService. AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class); List<AdGroupAdOperation> operations = new ArrayList<>(); ResponsiveSearchAd responsiveSearchAd = new ResponsiveSearchAd(); List<AssetLink> headlines = new ArrayList<>(); AssetLink pinnedHeadline = createAssetLinkForText("Cruise to Mars #" + System.currentTimeMillis()); // Set a pinning to always choose this asset for HEADLINE_1. Pinning is optional; if no pinning // is set, then headlines and descriptions will be rotated and the ones that perform best will // be used more often. pinnedHeadline.setPinnedField(ServedAssetFieldType.HEADLINE_1); headlines.add(pinnedHeadline); headlines.add(createAssetLinkForText("Best Space Cruise Line")); headlines.add(createAssetLinkForText("Experience the Stars")); responsiveSearchAd.setHeadlines(headlines.toArray(new AssetLink[0])); List<AssetLink> descriptions = new ArrayList<>(); descriptions.add(createAssetLinkForText("Buy your tickets now")); descriptions.add(createAssetLinkForText("Visit the Red Planet")); responsiveSearchAd.setDescriptions(descriptions.toArray(new AssetLink[0])); responsiveSearchAd.setFinalUrls(new String[] {"http://www.example.com/cruise"}); responsiveSearchAd.setPath1("all-inclusive"); responsiveSearchAd.setPath2("deals"); // Create ad group ad. AdGroupAd responsiveSearchAdGroupAd = new AdGroupAd(); responsiveSearchAdGroupAd.setAdGroupId(adGroupId); responsiveSearchAdGroupAd.setAd(responsiveSearchAd); // Optional: set the status. responsiveSearchAdGroupAd.setStatus(AdGroupAdStatus.PAUSED); // Create the operation. AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.setOperand(responsiveSearchAdGroupAd); adGroupAdOperation.setOperator(Operator.ADD); operations.add(adGroupAdOperation); // Add ad. AdGroupAdReturnValue result = adGroupAdService.mutate(operations.toArray(new AdGroupAdOperation[0])); for (AdGroupAd adGroupAdResult : result.getValue()) { ResponsiveSearchAd newAd = (ResponsiveSearchAd) adGroupAdResult.getAd(); System.out.printf( "New responsive search ad with ID %d was added.%n", adGroupAdResult.getAd().getId()); System.out.println("Headlines:"); for (AssetLink headline : newAd.getHeadlines()) { ServedAssetFieldType pinning = headline.getPinnedField(); System.out.printf(" %s%n", ((TextAsset) headline.getAsset()).getAssetText()); if (pinning != null) { System.out.printf(" (pinned to %s)%n", pinning); } } System.out.println("Descriptions:"); for (AssetLink description : newAd.getDescriptions()) { ServedAssetFieldType pinning = description.getPinnedField(); System.out.printf(" %s%n", ((TextAsset) description.getAsset()).getAssetText()); if (pinning != null) { System.out.printf(" (pinned to %s)%n", pinning); } } } } /** * Creates an {@link AssetLink} containing a {@link TextAsset} with the specified string. * * @param text the text for the text asset. * @return a new {@link AssetLink} */ private static AssetLink createAssetLinkForText(String text) { AssetLink assetLink = new AssetLink(); TextAsset textAsset = new TextAsset(); textAsset.setAssetText(text); assetLink.setAsset(textAsset); return assetLink; } }
Get the ad groups of 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.basicoperations; 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.utils.v201809.SelectorBuilder; import com.google.api.ads.adwords.axis.v201809.cm.AdGroup; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupPage; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupServiceInterface; 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.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.AdGroupField; 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 gets all ad groups in a campaign. To add an ad group, run * AddAdGroup.java. 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 GetAdGroups { private static final int PAGE_SIZE = 100; private static class GetAdGroupsParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private Long campaignId; } 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(); GetAdGroupsParams params = new GetAdGroupsParams(); 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"); } try { runExample(adWordsServices, session, params.campaignId); } 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 to use to find ad groups. * @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) throws RemoteException { // Get the AdGroupService. AdGroupServiceInterface adGroupService = adWordsServices.get(session, AdGroupServiceInterface.class); int offset = 0; boolean morePages = true; // Create selector. SelectorBuilder builder = new SelectorBuilder(); Selector selector = builder .fields(AdGroupField.Id, AdGroupField.Name) .orderAscBy(AdGroupField.Name) .offset(offset) .limit(PAGE_SIZE) .equals(AdGroupField.CampaignId, campaignId.toString()) .build(); while (morePages) { // Get all ad groups. AdGroupPage page = adGroupService.get(selector); // Display ad groups. if (page.getEntries() != null) { for (AdGroup adGroup : page.getEntries()) { System.out.printf("Ad group with name '%s' and ID %d was found.%n", adGroup.getName(), adGroup.getId()); } } else { System.out.println("No ad groups were found."); } offset += PAGE_SIZE; selector = builder.increaseOffsetBy(PAGE_SIZE).build(); morePages = offset < page.getTotalNumEntries(); } } }
Get all campaigns
// 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.basicoperations; 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.Campaign; import com.google.api.ads.adwords.axis.v201809.cm.CampaignPage; import com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface; 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.CampaignField; 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 all campaigns. To add a campaign, run AddCampaign.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class GetCampaigns { 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. CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class); int offset = 0; // Create selector. SelectorBuilder builder = new SelectorBuilder(); Selector selector = builder .fields(CampaignField.Id, CampaignField.Name) .orderAscBy(CampaignField.Name) .offset(offset) .limit(PAGE_SIZE) .build(); CampaignPage page; do { // Get all campaigns. page = campaignService.get(selector); // Display campaigns. if (page.getEntries() != null) { for (Campaign campaign : page.getEntries()) { System.out.printf("Campaign with name '%s' and ID %d was found.%n", campaign.getName(), campaign.getId()); } } else { System.out.println("No campaigns were found."); } offset += PAGE_SIZE; selector = builder.increaseOffsetBy(PAGE_SIZE).build(); } while (offset < page.getTotalNumEntries()); } }
Get all campaigns using AWQL
// 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.basicoperations; 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.ServiceQuery; 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.Campaign; import com.google.api.ads.adwords.axis.v201809.cm.CampaignPage; import com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface; 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.CampaignField; 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 all campaigns with AWQL. To add a campaign, run * AddCampaign.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class GetCampaignsWithAwql { 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. CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class); ServiceQuery serviceQuery = new ServiceQuery.Builder() .fields(CampaignField.Id, CampaignField.Name, CampaignField.Status) .orderBy(CampaignField.Name) .limit(0, PAGE_SIZE) .build(); CampaignPage page = null; do { serviceQuery.nextPage(page); // Get all campaigns. page = campaignService.query(serviceQuery.toString()); // Display campaigns. if (page.getEntries() != null) { for (Campaign campaign : page.getEntries()) { System.out.printf("Campaign with name '%s' and ID %d was found.%n", campaign.getName(), campaign.getId()); } } else { System.out.println("No campaigns were found."); } } while (serviceQuery.hasNext(page)); } }
Get expanded text ads in 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.basicoperations; 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.utils.v201809.SelectorBuilder; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdPage; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface; 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.ExpandedTextAd; 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.AdGroupAdField; 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 gets non-removed expanded text ads in an ad group. To add * expanded text ads, run AddExpandedTextAds.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class GetExpandedTextAds { private static final int PAGE_SIZE = 100; private static class GetExpandedTextAdsParams 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(); GetExpandedTextAdsParams params = new GetExpandedTextAdsParams(); 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 to use to find expanded text ads. * @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 AdGroupAdService. AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class); int offset = 0; boolean morePages = true; // Create selector. SelectorBuilder builder = new SelectorBuilder(); Selector selector = builder .fields( AdGroupAdField.Id, AdGroupAdField.Status, AdGroupAdField.HeadlinePart1, AdGroupAdField.HeadlinePart2, AdGroupAdField.Description) .orderAscBy(AdGroupAdField.Id) .offset(offset) .limit(PAGE_SIZE) .equals(AdGroupAdField.AdGroupId, adGroupId.toString()) .in(AdGroupAdField.Status, "ENABLED", "PAUSED") .equals("AdType", "EXPANDED_TEXT_AD") .build(); while (morePages) { // Get all ads. AdGroupAdPage page = adGroupAdService.get(selector); // Display ads. if (page.getEntries() != null && page.getEntries().length > 0) { for (AdGroupAd adGroupAd : page.getEntries()) { ExpandedTextAd expandedTextAd = (ExpandedTextAd) adGroupAd.getAd(); System.out.printf( "Expanded text ad with ID %d, status '%s', and headline '%s - %s' was found.%n", adGroupAd.getAd().getId(), adGroupAd.getStatus(), expandedTextAd.getHeadlinePart1(), expandedTextAd.getHeadlinePart2()); } } else { System.out.println("No expanded text ads were found."); } offset += PAGE_SIZE; selector = builder.increaseOffsetBy(PAGE_SIZE).build(); morePages = offset < page.getTotalNumEntries(); } } }
Get keywords in 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.basicoperations; 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.utils.v201809.SelectorBuilder; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface; 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.Keyword; 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.AdGroupCriterionField; 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.Arrays; /** * This example gets all ad group criteria in an account. To add keywords * criteria, run AddKeywords.java * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class GetKeywords { private static final int PAGE_SIZE = 100; private static class GetKeywordsParams 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(); GetKeywordsParams params = new GetKeywordsParams(); 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 to use to find keywords. * @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); int offset = 0; boolean morePages = true; // Create selector. SelectorBuilder builder = new SelectorBuilder(); Selector selector = builder .fields( AdGroupCriterionField.Id, AdGroupCriterionField.CriteriaType, AdGroupCriterionField.KeywordMatchType, AdGroupCriterionField.KeywordText) .orderAscBy(AdGroupCriterionField.KeywordText) .offset(offset) .limit(PAGE_SIZE) .in(AdGroupCriterionField.AdGroupId, adGroupId.toString()) .in(AdGroupCriterionField.CriteriaType, "KEYWORD") .build(); while (morePages) { // Get all ad group criteria. AdGroupCriterionPage page = adGroupCriterionService.get(selector); // Display ad group criteria. if (page.getEntries() != null && page.getEntries().length > 0) { // Display results. Arrays.stream(page.getEntries()) .map(adGroupCriterionResult -> (Keyword) adGroupCriterionResult.getCriterion()) .forEach( keyword -> System.out.printf( "Keyword with text '%s', match type '%s', criteria type '%s'," + " and ID %d was found.%n", keyword.getText(), keyword.getMatchType(), keyword.getType(), keyword.getId())); } else { System.out.println("No ad group criteria were found."); } offset += PAGE_SIZE; selector = builder.increaseOffsetBy(PAGE_SIZE).build(); morePages = offset < page.getTotalNumEntries(); } } }
Get responsive search ads in an ad group
// Copyright 2018 Google LLC // // 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 // // https://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.basicoperations; 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.utils.v201809.SelectorBuilder; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdPage; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdType; 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.AssetLink; import com.google.api.ads.adwords.axis.v201809.cm.ResponsiveSearchAd; import com.google.api.ads.adwords.axis.v201809.cm.Selector; import com.google.api.ads.adwords.axis.v201809.cm.ServedAssetFieldType; import com.google.api.ads.adwords.axis.v201809.cm.TextAsset; 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.AdGroupAdField; 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 gets non-removed responsive search ads in an ad group. To add responsive search ads, * run AddResponsiveSearchAds.java. 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 GetResponsiveSearchAds { private static final int PAGE_SIZE = 100; private static class GetResponsiveSearchAdsParams 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(); GetResponsiveSearchAdsParams params = new GetResponsiveSearchAdsParams(); 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 to use to find expanded text ads. * @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 AdGroupAdService. AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class); int offset = 0; boolean morePages = true; // Create selector to get all of the ads for the ad group. SelectorBuilder builder = new SelectorBuilder(); Selector selector = builder .fields( AdGroupAdField.Id, AdGroupAdField.Status, AdGroupAdField.ResponsiveSearchAdHeadlines, AdGroupAdField.ResponsiveSearchAdDescriptions) .orderAscBy(AdGroupAdField.Id) .offset(offset) .limit(PAGE_SIZE) .equals(AdGroupAdField.AdGroupId, adGroupId.toString()) .in(AdGroupAdField.Status, "ENABLED", "PAUSED") .equals("AdType", AdType.RESPONSIVE_SEARCH_AD.getValue()) .build(); int totalEntries = 0; while (morePages) { // Get all ads. AdGroupAdPage page = adGroupAdService.get(selector); // Display ads. if (page.getEntries() != null && page.getEntries().length > 0) { totalEntries = page.getTotalNumEntries(); for (AdGroupAd adGroupAd : page.getEntries()) { ResponsiveSearchAd responsiveSearchAd = (ResponsiveSearchAd) adGroupAd.getAd(); System.out.printf( "Responsive search ad with ID %d, status '%s' was found.%n", adGroupAd.getAd().getId(), adGroupAd.getStatus()); System.out.println("Headlines:"); for (AssetLink headline : responsiveSearchAd.getHeadlines()) { ServedAssetFieldType pinning = headline.getPinnedField(); System.out.printf(" %s%n", ((TextAsset) headline.getAsset()).getAssetText()); if (pinning != null) { System.out.printf(" (pinned to %s)%n", pinning); } } System.out.println("Descriptions:"); for (AssetLink description : responsiveSearchAd.getDescriptions()) { ServedAssetFieldType pinning = description.getPinnedField(); System.out.printf(" %s%n", ((TextAsset) description.getAsset()).getAssetText()); if (pinning != null) { System.out.printf(" (pinned to %s)%n", pinning); } } } } offset += PAGE_SIZE; selector = builder.increaseOffsetBy(PAGE_SIZE).build(); morePages = offset < page.getTotalNumEntries(); } System.out.printf("Ad group ID %d has %d responsive search ads.%n", adGroupId, totalEntries); } }
Pause an ad
// 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.basicoperations; 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.Ad; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdStatus; 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.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 updates status for a given ad. To get ads, run GetExpandedTextAds. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class PauseAd { private static class PauseAdParams extends CodeSampleParams { @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true) private Long adGroupId; @Parameter(names = ArgumentNames.AD_ID, required = true) private Long adId; } 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(); PauseAdParams params = new PauseAdParams(); 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"); params.adId = Long.parseLong("INSERT_AD_ID_HERE"); } try { runExample(adWordsServices, session, params.adGroupId, params.adId); } 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 for the ad. * @param adId the ID of the ad to pause. * @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, Long adId) throws RemoteException { // Get the AdGroupAdService. AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class); // Create ad with updated status. Ad ad = new Ad(); ad.setId(adId); AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.setAdGroupId(adGroupId); adGroupAd.setAd(ad); adGroupAd.setStatus(AdGroupAdStatus.PAUSED); // Create operations. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.setOperand(adGroupAd); operation.setOperator(Operator.SET); AdGroupAdOperation[] operations = new AdGroupAdOperation[] {operation}; // Update ad. AdGroupAdReturnValue result = adGroupAdService.mutate(operations); // Display ads. for (AdGroupAd adGroupAdResult : result.getValue()) { System.out.printf("Ad with ID %d, type '%s', and status '%s' was updated.%n", adGroupAdResult.getAd().getId(), adGroupAdResult.getAd().getAdType(), adGroupAdResult.getStatus()); } } }
Remove an ad
// 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.basicoperations; 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.Ad; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface; 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.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 removes an ad using the 'REMOVE' operator. To get ads, run * GetTextAds.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class RemoveAd { private static class RemoveAdParams extends CodeSampleParams { @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true) private Long adGroupId; @Parameter(names = ArgumentNames.AD_ID, required = true) private Long adId; } 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(); RemoveAdParams params = new RemoveAdParams(); 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"); params.adId = Long.parseLong("INSERT_AD_ID_HERE"); } try { runExample(adWordsServices, session, params.adGroupId, params.adId); } 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 for the ad. * @param adId the ID of the ad to remove. * @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, long adId) throws RemoteException { // Get the AdGroupAdService. AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class); // Create base class ad to avoid setting type specific fields. Ad ad = new Ad(); ad.setId(adId); // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.setAdGroupId(adGroupId); adGroupAd.setAd(ad); // Create operations. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.setOperand(adGroupAd); operation.setOperator(Operator.REMOVE); AdGroupAdOperation[] operations = new AdGroupAdOperation[] {operation}; // Remove ad. AdGroupAdReturnValue result = adGroupAdService.mutate(operations); // Display ads. for (AdGroupAd adGroupAdResult : result.getValue()) { System.out.printf("Ad with ID %d and type '%s' was removed.%n", adGroupAdResult.getAd().getId(), adGroupAdResult.getAd().getAdType()); } } }
Remove 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.basicoperations; 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.AdGroup; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupStatus; 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.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 deletes an ad group by setting the status to 'REMOVED'. 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 RemoveAdGroup { private static class RemoveAdGroupParams 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(); RemoveAdGroupParams params = new RemoveAdGroupParams(); 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 to remove. * @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 AdGroupService. AdGroupServiceInterface adGroupService = adWordsServices.get(session, AdGroupServiceInterface.class); // Create ad group with REMOVED status. AdGroup adGroup = new AdGroup(); adGroup.setId(adGroupId); adGroup.setStatus(AdGroupStatus.REMOVED); // Create operations. AdGroupOperation operation = new AdGroupOperation(); operation.setOperand(adGroup); operation.setOperator(Operator.SET); AdGroupOperation[] operations = new AdGroupOperation[] {operation}; // Remove ad group. AdGroupReturnValue result = adGroupService.mutate(operations); // Display ad groups. for (AdGroup adGroupResult : result.getValue()) { System.out.printf("Ad group with name '%s' and ID %d was removed.%n", adGroupResult.getName(), adGroupResult.getId()); } } }
Remove 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.basicoperations; 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.Campaign; import com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation; import com.google.api.ads.adwords.axis.v201809.cm.CampaignReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.CampaignStatus; 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 removes a campaign by setting the status to 'REMOVED'. 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 RemoveCampaign { private static class RemoveCampaignParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private Long campaignId; } 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(); RemoveCampaignParams params = new RemoveCampaignParams(); 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"); } try { runExample(adWordsServices, session, params.campaignId); } 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 to remove. * @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) throws RemoteException { // Get the CampaignService. CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class); // Create campaign with REMOVED status. Campaign campaign = new Campaign(); campaign.setId(campaignId); campaign.setStatus(CampaignStatus.REMOVED); // Create operations. CampaignOperation operation = new CampaignOperation(); operation.setOperand(campaign); operation.setOperator(Operator.SET); CampaignOperation[] operations = new CampaignOperation[] {operation}; // Remove campaign. CampaignReturnValue result = campaignService.mutate(operations); // Display campaigns. for (Campaign campaignResult : result.getValue()) { System.out.printf("Campaign with name '%s' and ID %d was removed.%n", campaignResult.getName(), campaignResult.getId()); } } }
Remove a keyword
// 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.basicoperations; 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.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.Criterion; 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 removes an ad group criterion using the 'REMOVE' operator. To * get ad group criteria, run GetKeywords.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class RemoveKeyword { private static class RemoveKeywordParams extends CodeSampleParams { @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true) private Long adGroupId; @Parameter(names = ArgumentNames.CRITERION_ID, required = true) private Long criterionId; } 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(); RemoveKeywordParams params = new RemoveKeywordParams(); 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"); params.criterionId = Long.parseLong("INSERT_CRITERION_ID_HERE"); } try { runExample(adWordsServices, session, params.adGroupId, params.criterionId); } 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 for the keyword criterion. * @param criterionId the ID of the keyword criterion to remove. * @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, long criterionId) throws RemoteException { // Get the AdGroupCriterionService. AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class); // Create base class criterion to avoid setting keyword specific fields. Criterion criterion = new Criterion(); criterion.setId(criterionId); // Create ad group criterion. AdGroupCriterion adGroupCriterion = new AdGroupCriterion(); adGroupCriterion.setAdGroupId(adGroupId); adGroupCriterion.setCriterion(criterion); // Create operations. AdGroupCriterionOperation operation = new AdGroupCriterionOperation(); operation.setOperand(adGroupCriterion); operation.setOperator(Operator.REMOVE); AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] {operation}; // Remove ad group criteria. AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations); // Display ad group criteria. for (AdGroupCriterion adGroupCriterionResult : result.getValue()) { System.out.printf("Ad group criterion with ad group ID %d, criterion ID %d, and type " + "'%s' was removed.%n", adGroupCriterionResult.getAdGroupId(), adGroupCriterionResult.getCriterion().getId(), adGroupCriterionResult.getCriterion().getCriterionType()); } } }
Update 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.basicoperations; 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.AdGroup; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupOperation; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.AdGroupStatus; 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.BiddingStrategyConfiguration; import com.google.api.ads.adwords.axis.v201809.cm.Bids; import com.google.api.ads.adwords.axis.v201809.cm.CpcBid; import com.google.api.ads.adwords.axis.v201809.cm.Money; 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 javax.annotation.Nullable; /** * This example updates the CPC bid and status for a given 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 UpdateAdGroup { private static class UpdateAdGroupParams extends CodeSampleParams { @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true) private Long adGroupId; @Parameter(names = ArgumentNames.CPC_BID_MICRO_AMOUNT) private Long cpcBidMicroAmount; } 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(); UpdateAdGroupParams params = new UpdateAdGroupParams(); 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"); // Set this to null if you do not want to update the CPC bid. params.cpcBidMicroAmount = Long.parseLong("INSERT_CPC_BID_MICRO_AMOUNT_HERE"); } try { runExample(adWordsServices, session, params.adGroupId, params.cpcBidMicroAmount); } 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 to update. * @param bidMicroAmount the optional bid amount in micros to use for the ad group bid. * @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, @Nullable Long bidMicroAmount) throws RemoteException { // Get the AdGroupService. AdGroupServiceInterface adGroupService = adWordsServices.get(session, AdGroupServiceInterface.class); // Create an ad group with the specified ID. AdGroup adGroup = new AdGroup(); adGroup.setId(adGroupId); // Update the CPC bid if specified. if (bidMicroAmount != null) { BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); Money cpcBidMoney = new Money(); cpcBidMoney.setMicroAmount(bidMicroAmount); CpcBid cpcBid = new CpcBid(); cpcBid.setBid(cpcBidMoney); biddingStrategyConfiguration.setBids(new Bids[] {cpcBid}); adGroup.setBiddingStrategyConfiguration(biddingStrategyConfiguration); } // Pause the ad group. adGroup.setStatus(AdGroupStatus.PAUSED); // Create operations. AdGroupOperation operation = new AdGroupOperation(); operation.setOperand(adGroup); operation.setOperator(Operator.SET); AdGroupOperation[] operations = new AdGroupOperation[] {operation}; // Update ad group. AdGroupReturnValue result = adGroupService.mutate(operations); // Display ad groups. for (AdGroup adGroupResult : result.getValue()) { BiddingStrategyConfiguration biddingStrategyConfiguration = adGroupResult.getBiddingStrategyConfiguration(); // Find the CpcBid in the bidding strategy configuration's bids collection. Long cpcBidMicros = null; if (biddingStrategyConfiguration != null) { if (biddingStrategyConfiguration.getBids() != null) { for (Bids bid : biddingStrategyConfiguration.getBids()) { if (bid instanceof CpcBid) { cpcBidMicros = ((CpcBid) bid).getBid().getMicroAmount(); break; } } } } System.out.printf( "Ad group with ID %d and name '%s' updated to have status '%s' and CPC bid %d%n", adGroupResult.getId(), adGroupResult.getName(), adGroupResult.getStatus(), cpcBidMicros); } } }
Update 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.basicoperations; 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.Campaign; import com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation; import com.google.api.ads.adwords.axis.v201809.cm.CampaignReturnValue; import com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface; import com.google.api.ads.adwords.axis.v201809.cm.CampaignStatus; 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 updates a campaign by setting the status to PAUSED. 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 UpdateCampaign { private static class UpdateCampaignParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private Long campaignId; } 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(); UpdateCampaignParams params = new UpdateCampaignParams(); 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"); } try { runExample(adWordsServices, session, params.campaignId); } 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 to update. * @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) throws RemoteException { // Get the CampaignService. CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class); // Create campaign with updated status. Campaign campaign = new Campaign(); campaign.setId(campaignId); campaign.setStatus(CampaignStatus.PAUSED); // Create operations. CampaignOperation operation = new CampaignOperation(); operation.setOperand(campaign); operation.setOperator(Operator.SET); CampaignOperation[] operations = new CampaignOperation[] {operation}; // Update campaign. CampaignReturnValue result = campaignService.mutate(operations); // Display campaigns. for (Campaign campaignResult : result.getValue()) { System.out.printf("Campaign with name '%s', ID %d, and budget delivery method '%s' " + "was updated.%n", campaignResult.getName(), campaignResult.getId(), campaignResult.getBudget().getDeliveryMethod()); } } }
Update a keyword
// 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.basicoperations; 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.ApiError; import com.google.api.ads.adwords.axis.v201809.cm.ApiException; import com.google.api.ads.adwords.axis.v201809.cm.BidSource; import com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion; import com.google.api.ads.adwords.axis.v201809.cm.BiddingStrategyConfiguration; import com.google.api.ads.adwords.axis.v201809.cm.Bids; import com.google.api.ads.adwords.axis.v201809.cm.CpcBid; import com.google.api.ads.adwords.axis.v201809.cm.Criterion; import com.google.api.ads.adwords.axis.v201809.cm.Money; 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 updates the bid of a keyword. To add a keyword, run * AddKeywords.java. * * <p>Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class UpdateKeyword { private static class UpdateKeywordParams extends CodeSampleParams { @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true) private Long adGroupId; @Parameter(names = ArgumentNames.KEYWORD_ID, required = true) private Long keywordId; } 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(); UpdateKeywordParams params = new UpdateKeywordParams(); 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"); params.keywordId = Long.parseLong("INSERT_KEYWORD_ID_HERE"); } try { runExample(adWordsServices, session, params.adGroupId, params.keywordId); } 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 for the criterion. * @param keywordId the ID of the criterion to update. * @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, Long keywordId) throws RemoteException { // Get the AdGroupCriterionService. AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class); // Create ad group criterion with updated bid. Criterion criterion = new Criterion(); criterion.setId(keywordId); BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion(); biddableAdGroupCriterion.setAdGroupId(adGroupId); biddableAdGroupCriterion.setCriterion(criterion); // Create bids. BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); CpcBid bid = new CpcBid(); bid.setBid(new Money(null, 10000000L)); biddingStrategyConfiguration.setBids(new Bids[] {bid}); biddableAdGroupCriterion.setBiddingStrategyConfiguration(biddingStrategyConfiguration); // Create operations. AdGroupCriterionOperation operation = new AdGroupCriterionOperation(); operation.setOperand(biddableAdGroupCriterion); operation.setOperator(Operator.SET); AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] {operation}; // Update ad group criteria. AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations); // Display ad group criteria. for (AdGroupCriterion adGroupCriterionResult : result.getValue()) { if (adGroupCriterionResult instanceof BiddableAdGroupCriterion) { biddableAdGroupCriterion = (BiddableAdGroupCriterion) adGroupCriterionResult; CpcBid criterionCpcBid = null; // Find the criterion-level CpcBid among the keyword's bids. for (Bids bids : biddableAdGroupCriterion.getBiddingStrategyConfiguration().getBids()) { if (bids instanceof CpcBid) { CpcBid cpcBid = (CpcBid) bids; if (BidSource.CRITERION.equals(cpcBid.getCpcBidSource())) { criterionCpcBid = cpcBid; } } } System.out.printf( "Ad group criterion with ad group ID %d, criterion ID %d, type " + "'%s', and bid %d was updated.%n", biddableAdGroupCriterion.getAdGroupId(), biddableAdGroupCriterion.getCriterion().getId(), biddableAdGroupCriterion.getCriterion().getCriterionType(), criterionCpcBid.getBid().getMicroAmount()); } } } }