Search in sources :

Example 21 with ApiException

use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.

the class GetAdGroupBidModifier method main.

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);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 22 with ApiException

use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.

the class AddExpandedTextAds method runExample.

/**
 * 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())));
}
Also used : Arrays(java.util.Arrays) Parameter(com.beust.jcommander.Parameter) ArrayList(java.util.ArrayList) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) ArgumentNames(com.google.api.ads.adwords.lib.utils.examples.ArgumentNames) Credential(com.google.api.client.auth.oauth2.Credential) AdGroupAdReturnValue(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue) AdGroupAdStatus(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdStatus) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Operator(com.google.api.ads.adwords.axis.v201809.cm.Operator) CodeSampleParams(com.google.api.ads.common.lib.utils.examples.CodeSampleParams) ExpandedTextAd(com.google.api.ads.adwords.axis.v201809.cm.ExpandedTextAd) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdGroupAd(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd) List(java.util.List) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdGroupAdOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) AdGroupAdServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface) AdGroupAd(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd) AdGroupAdReturnValue(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue) AdGroupAdServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface) ArrayList(java.util.ArrayList) ExpandedTextAd(com.google.api.ads.adwords.axis.v201809.cm.ExpandedTextAd) AdGroupAdOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation)

Example 23 with ApiException

use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.

the class AddExpandedTextAds method main.

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);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 24 with ApiException

use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.

the class GetAdGroups method runExample.

/**
 * 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();
    }
}
Also used : AdGroupServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupServiceInterface) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) AdGroupPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupPage) AdGroup(com.google.api.ads.adwords.axis.v201809.cm.AdGroup) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Example 25 with ApiException

use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.

the class MigrateToExtensionSettings method runExample.

/**
 * 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 all of the feeds for the session's account.
    List<Feed> feeds = getFeeds(adWordsServices, session);
    for (Feed feed : feeds) {
        // Retrieve all the sitelinks from the current feed.
        Map<Long, SiteLinkFromFeed> feedItems = getSiteLinksFromFeed(adWordsServices, session, feed);
        // Get all the instances where a sitelink from this feed has been added to a campaign.
        List<CampaignFeed> campaignFeeds = getCampaignFeeds(adWordsServices, session, feed, PLACEHOLDER_SITELINKS);
        Set<Long> allFeedItemsToDelete = Sets.newHashSet();
        for (CampaignFeed campaignFeed : campaignFeeds) {
            // Retrieve the sitelinks that have been associated with this campaign.
            Set<Long> feedItemIds = getFeedItemIdsForCampaign(campaignFeed);
            ExtensionSettingPlatform platformRestrictions = getPlatformRestictionsForCampaign(campaignFeed);
            if (feedItemIds.isEmpty()) {
                System.out.printf("Migration skipped for campaign feed with campaign ID %d " + "and feed ID %d because no mapped feed item IDs were found in the " + "campaign feed's matching function.%n", campaignFeed.getCampaignId(), campaignFeed.getFeedId());
            } else {
                // Delete the campaign feed that associates the sitelinks from the feed to the campaign.
                deleteCampaignFeed(adWordsServices, session, campaignFeed);
                // Create extension settings instead of sitelinks.
                createExtensionSetting(adWordsServices, session, feedItems, campaignFeed, feedItemIds, platformRestrictions);
                // Mark the sitelinks from the feed for deletion.
                allFeedItemsToDelete.addAll(feedItemIds);
            }
        }
        // Delete all the sitelinks from the feed.
        deleteOldFeedItems(adWordsServices, session, allFeedItemsToDelete, feed);
    }
}
Also used : CampaignFeed(com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed) ExtensionSettingPlatform(com.google.api.ads.adwords.axis.v201809.cm.ExtensionSettingPlatform) CampaignFeed(com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed) Feed(com.google.api.ads.adwords.axis.v201809.cm.Feed)

Aggregations

ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)102 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)100 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)100 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)100 RemoteException (java.rmi.RemoteException)100 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)99 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)98 AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)97 Credential (com.google.api.client.auth.oauth2.Credential)97 SelectorBuilder (com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder)47 ArrayList (java.util.ArrayList)23 Selector (com.google.api.ads.adwords.axis.v201809.cm.Selector)21 Money (com.google.api.ads.adwords.axis.v201809.cm.Money)18 AdGroupAd (com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd)17 AdGroupAdServiceInterface (com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface)16 Campaign (com.google.api.ads.adwords.axis.v201809.cm.Campaign)15 CampaignServiceInterface (com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface)14 Budget (com.google.api.ads.adwords.axis.v201809.cm.Budget)13 BiddingStrategyConfiguration (com.google.api.ads.adwords.axis.v201809.cm.BiddingStrategyConfiguration)12 IOException (java.io.IOException)12