Google Adwords Java Integration

Step 1: Create Google AdwordSession configuration

package com.integration.adwords.config;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
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 org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by tmichels on 7/31/15.
 */

@Configuration
public class GoogleAdwordsConfig {

    @Value("${GOOGLE_ADWORD_CLIENTID}")
    private String googleAdWordClientId;

    @Value("${GOOGLE_ADWORD_SECRET}")
    private String googleAdwordSecet;

    @Value("${GOOGLE_ADWORDS_DEV_TOKEN}")
    private String googleAdwordDevToken;

    @Value("${GOOGLE_ADWORDS_REFRESH_TOKEN}")
    private String googleAdwordRefreshToken;

    @Value("${GOOGLE_ADWORDS_USER_AGENT}")
    private String googleAdwordUserAgent;

    @Value("${GOOGLE_ADWORDS_CLIENT_CUSTOMER_ID}")
    private String googleAdwordClientCustomerId;

    @Bean
    public Credential credential() throws ValidationException, OAuthException {
        Credential credential = new OfflineCredentials.Builder()
                                .forApi(OfflineCredentials.Api.ADWORDS)
                                .withClientSecrets(googleAdWordClientId, googleAdwordSecet)
                                .withRefreshToken(googleAdwordRefreshToken)
                                .build()
                                .generateCredential();
        return credential;
    }

    @Bean
    public AdWordsSession adWordsSession(Credential credential) throws ValidationException {
        AdWordsSession adWordsSession = new AdWordsSession.Builder()
                                        .withDeveloperToken(googleAdwordDevToken)
                                        .withOAuth2Credential(credential)
                                        .withClientCustomerId(googleAdwordClientCustomerId)
                                        .withUserAgent(googleAdwordUserAgent)


                .build();
        return adWordsSession;
    }
}

2. Create AdWord Service to export KeyWords, Campaigns, AdGroups and Ads.

package com.integration.adwords.service;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201506.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201506.cm.*;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.selectorfields.v201502.cm.CampaignField;
import com.google.api.ads.adwords.lib.selectorfields.v201506.cm.AdGroupAdField;
import com.google.api.ads.adwords.lib.selectorfields.v201506.cm.AdGroupCriterionField;
import com.google.api.ads.adwords.lib.selectorfields.v201506.cm.AdGroupField;
import com.integration.file.FileConverter;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tmichels on 7/31/15.
 */

@Service
public class GoogleAdwordService {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(GoogleAdwordService.class);

    private static final int PAGE_SIZE = 100;

    private static final String CAMPAIGNFILENAME="adwords/google/googleAdwordCampaign.csv";
    private static final String KEYWORDFILENAME="adwords/google/googleAdwordKeywords.csv";
    private static final String ADGROUPFILENAME="adwords/google/googleAdwordAdGroup.csv";
    private static final String ADSFILENAME="adwords/google/googleAdwordAds.csv";

    @Autowired
    AdWordsSession adWordsSession;

    @Autowired
    FileConverter fileConverter;

    public void getCampaigns() throws RemoteException {
        List<String> campaignColumns = new ArrayList<>();
        List<String> campaignData = new ArrayList<>();

        // Get the CampaignService.
        CampaignServiceInterface campaignService =
                new AdWordsServices().get(adWordsSession, CampaignServiceInterface.class);

        int offset = 0;

        // Create selector.
        SelectorBuilder builder = new SelectorBuilder();
        Selector selector = builder
                .fields(CampaignField.Id,
                        CampaignField.Name,
                        CampaignField.AdServingOptimizationStatus,
                        CampaignField.AdvertisingChannelSubType,
                        CampaignField.AdvertisingChannelType,
                        CampaignField.BiddingStrategyId,
                        CampaignField.BiddingStrategyName,
                        CampaignField.BiddingStrategyType,
                        CampaignField.BidType,
                        CampaignField.BudgetId,
                        CampaignField.BudgetName,
                        CampaignField.BudgetReferenceCount,
                        CampaignField.BudgetStatus,
                        CampaignField.DeliveryMethod,
                        CampaignField.Eligible,
                        CampaignField.EndDate,
                        CampaignField.FrequencyCapMaxImpressions,
                        CampaignField.Labels,
                        CampaignField.StartDate,
                        CampaignField.TrackingUrlTemplate,
                        CampaignField.UrlCustomParameters)
                .orderAscBy(CampaignField.Id)
                .offset(offset)
                .limit(PAGE_SIZE)
                .build();

        campaignColumns.add(CampaignField.Id.toString());
        campaignColumns.add(CampaignField.Name.toString());
        campaignColumns.add(CampaignField.AdServingOptimizationStatus.toString());
        campaignColumns.add(CampaignField.AdvertisingChannelSubType.toString());
        campaignColumns.add(CampaignField.AdvertisingChannelType.toString());
        campaignColumns.add(CampaignField.BiddingStrategyId.toString());
        campaignColumns.add(CampaignField.BiddingStrategyName.toString());
        campaignColumns.add(CampaignField.BiddingStrategyType.toString());
        campaignColumns.add(CampaignField.BidType.toString());
        campaignColumns.add(CampaignField.BudgetId.toString());
        campaignColumns.add(CampaignField.BudgetName.toString());
        campaignColumns.add(CampaignField.BudgetReferenceCount.toString());
        campaignColumns.add(CampaignField.BudgetStatus.toString());
        campaignColumns.add(CampaignField.DeliveryMethod.toString());
        campaignColumns.add(CampaignField.Eligible.toString());
        campaignColumns.add(CampaignField.EndDate.toString());
        campaignColumns.add(CampaignField.FrequencyCapMaxImpressions.toString());
        campaignColumns.add(CampaignField.Labels.toString());
        campaignColumns.add(CampaignField.StartDate.toString());
        campaignColumns.add(CampaignField.TrackingUrlTemplate.toString());
        campaignColumns.add(CampaignField.UrlCustomParameters.toString());

        CampaignPage page = null;
        do {
            // Get all campaigns.
            page = campaignService.get(selector);

            // Display campaigns.
            if (page.getEntries() != null) {
                for (Campaign campaign : page.getEntries()) {
                    campaignData.add(campaign.getId().toString());
                    campaignData.add(campaign.getName());
                    campaignData.add(campaign.getAdServingOptimizationStatus()!=null? campaign.getAdServingOptimizationStatus().toString() : "");
                    campaignData.add(campaign.getAdvertisingChannelSubType() != null ? campaign.getAdvertisingChannelSubType().toString() : "");
                    campaignData.add(campaign.getAdvertisingChannelType().toString());
                    campaignData.add(campaign.getBiddingStrategyConfiguration().getBiddingStrategyId() != null ? campaign.getBiddingStrategyConfiguration().getBiddingStrategyId().toString() : "");
                    campaignData.add(campaign.getBiddingStrategyConfiguration().getBiddingStrategyName());
                    campaignData.add(campaign.getBiddingStrategyConfiguration().getBiddingStrategyType() != null ? campaign.getBiddingStrategyConfiguration().getBiddingStrategyType().getValue() : "");
                    campaignData.add(campaign.getBudget().getBudgetId() != null ? campaign.getBudget().getBudgetId().toString() : "");
                    campaignData.add(campaign.getBudget().getName());
                    campaignData.add(campaign.getBudget().getReferenceCount() != null ? campaign.getBudget().getReferenceCount().toString() : "");
                    campaignData.add(campaign.getBudget().getStatus() != null ? campaign.getBudget().getStatus().getValue() : "");
                    campaignData.add(campaign.getBudget().getDeliveryMethod() != null ? campaign.getBudget().getDeliveryMethod().getValue() : "");
                    campaignData.add(campaign.getBudget().getIsExplicitlyShared() != null ? campaign.getBudget().getIsExplicitlyShared().toString() : "");
                    campaignData.add(campaign.getEndDate());
                    campaignData.add(campaign.getFrequencyCap()!=null && campaign.getFrequencyCap().getImpressions() != null ? campaign.getFrequencyCap().getImpressions().toString() : "");
                    campaignData.add(campaign.getLabels() != null ? campaign.getLabels().toString() : "");
                    campaignData.add(campaign.getStartDate());
                    campaignData.add(campaign.getTrackingUrlTemplate());
                    campaignData.add(campaign.getUrlCustomParameters()!=null &&  campaign.getUrlCustomParameters().getParameters() != null ? campaign.getUrlCustomParameters().getParameters().toString() : "");
                }
            } else {
                logger.info("No campaigns were found.");
            }

            offset += PAGE_SIZE;
            selector = builder.increaseOffsetBy(PAGE_SIZE).build();
        } while (offset < page.getTotalNumEntries());

        fileConverter.convertToCSV(campaignData, campaignColumns, CAMPAIGNFILENAME);
    }

    public void getKeyWords() throws RemoteException {
        List<String> campaignColumns = new ArrayList<>();
        List<String> campaignData = new ArrayList<>();

        // Get the AdGroupCriterionService.
        AdGroupCriterionServiceInterface adGroupCriterionService =
                new AdWordsServices().get(adWordsSession, AdGroupCriterionServiceInterface.class);

        int offset = 0;
        boolean morePages = true;

        // Create selector.
        SelectorBuilder builder = new SelectorBuilder();
        Selector selector = builder
                .fields(
                        AdGroupCriterionField.Id,
                        AdGroupCriterionField.AdGroupId,
                        AdGroupCriterionField.KeywordMatchType,
                        AdGroupCriterionField.KeywordText)
                .offset(offset)
                .limit(PAGE_SIZE)
                .equals(AdGroupCriterionField.CriteriaType, "KEYWORD")
                .build();

        campaignColumns.add(AdGroupCriterionField.Id.toString());
        campaignColumns.add(AdGroupCriterionField.AdGroupId.toString());
        campaignColumns.add(AdGroupCriterionField.KeywordMatchType.toString());
        campaignColumns.add(AdGroupCriterionField.KeywordText.toString());

        while (morePages) {
            AdGroupCriterionPage page = adGroupCriterionService.get(selector);

            if (page.getEntries() != null && page.getEntries().length > 0) {
                for (AdGroupCriterion adGroupCriterionResult : page.getEntries()) {
                    campaignData.add(adGroupCriterionResult.getAdGroupId().toString());
                    campaignData.add(adGroupCriterionResult.getCriterion().getId().toString());
                    campaignData.add(((Keyword) adGroupCriterionResult.getCriterion()).getText());
                    campaignData.add(((Keyword) adGroupCriterionResult.getCriterion()).getMatchType().toString());
                }
            } else {
                logger.info("No keywords were found.");
            }
            offset += PAGE_SIZE;
            selector = builder.increaseOffsetBy(PAGE_SIZE).build();
            morePages = offset < page.getTotalNumEntries();
        }

        fileConverter.convertToCSV(campaignData, campaignColumns, KEYWORDFILENAME);
    }

    public void getTextAds() throws RemoteException {
        List<String> campaignColumns = new ArrayList<>();
        List<String> campaignData = new ArrayList<>();

        AdGroupAdServiceInterface adGroupAdService =
                new AdWordsServices().get(adWordsSession, AdGroupAdServiceInterface.class);

        int offset = 0;
        boolean morePages = true;

        // Create selector.
        SelectorBuilder builder = new SelectorBuilder();
        Selector selector = builder
                .fields(AdGroupAdField.Id,
                        AdGroupAdField.AdGroupId,
                        AdGroupAdField.Status)
                .orderAscBy(AdGroupAdField.Id)
                .offset(offset)
                .limit(PAGE_SIZE)
                .in(AdGroupAdField.Status, "ENABLED", "PAUSED", "DISABLED")
                .build();

        campaignColumns.add(AdGroupAdField.Id.toString());
        campaignColumns.add(AdGroupAdField.AdGroupId.toString());
        campaignColumns.add(AdGroupAdField.Status.toString());

        while (morePages) {
            AdGroupAdPage page = adGroupAdService.get(selector);

            if (page.getEntries() != null && page.getEntries().length > 0) {
                for (AdGroupAd adGroupAd : page.getEntries()) {
                    campaignData.add(adGroupAd.getAd().getId().toString());
                    campaignData.add(adGroupAd.getAd().getAdType().toString());
                    campaignData.add(adGroupAd.getStatus().toString());
                }
            } else {
                logger.info("No text ads were found");
            }

            offset += PAGE_SIZE;
            selector = builder.increaseOffsetBy(PAGE_SIZE).build();
            morePages = offset < page.getTotalNumEntries();
        }

        fileConverter.convertToCSV(campaignData, campaignColumns, ADSFILENAME);

    }
    public void getAdGroups() throws RemoteException {
        List<String> campaignColumns = new ArrayList<>();
        List<String> campaignData = new ArrayList<>();

        AdGroupServiceInterface adGroupService = new AdWordsServices().get(adWordsSession, AdGroupServiceInterface.class);

        int offset = 0;
        boolean morePages = true;

        // Create selector.
        SelectorBuilder builder = new SelectorBuilder();
        Selector selector = builder
                .fields(AdGroupField.Id,
                        AdGroupField.Name,
                        AdGroupField.Status)
                .orderAscBy(AdGroupField.Name)
                .offset(offset)
                .limit(PAGE_SIZE)
                .build();

        campaignColumns.add(AdGroupField.Id.toString());
        campaignColumns.add(AdGroupField.Name.toString());
        campaignColumns.add(AdGroupField.Status.toString());

        while (morePages) {
            AdGroupPage page = adGroupService.get(selector);
            // Display ad groups.
            if (page.getEntries() != null) {
                for (AdGroup adGroup : page.getEntries()) {
                    campaignData.add(adGroup.getId().toString());
                    campaignData.add(adGroup.getName().toString());
                    campaignData.add(adGroup.getStatus()!=null ? adGroup.getStatus().getValue() : "");
                }
            } else {
                logger.info("No group ads were found.");
            }

            offset += PAGE_SIZE;
            selector = builder.increaseOffsetBy(PAGE_SIZE).build();
            morePages = offset < page.getTotalNumEntries();
        }
        fileConverter.convertToCSV(campaignData, campaignColumns, ADGROUPFILENAME);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: