Microsoft Bing Adwords Java Integration

Step 1: Setup Bing BulkServiceManager Configuration

package com.integration.adwords.config;
import com.microsoft.bingads.*;
import com.microsoft.bingads.bulk.BulkServiceManager;
import com.microsoft.bingads.campaignmanagement.ICampaignManagementService;
import com.microsoft.bingads.internal.OAuthService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * Created by tmichels on 7/31/15.
 */
@Configuration
public class BingAdwordsConfig {
    @Value("${BING_ADS_CLIENTID}")
    private String bingAdsClientId;
    @Value("${BING_ADS_CLIENT_SECRET}")
    private String bingAdsClientSecret;
    @Value("${BING_ADS_ACCOUNTID}")
    private String bingAdsAccountId;
    @Value("${BING_ADS_CUSTOMERID}")
    private String bingAdsCustomerId;
    @Value("${BING_ADS_DEVELOPER_TOKEN}")
    private String bingAdsDeveloperToken;
    @Value("${BING_ADS_USERNAME}")
    private String bingAdsUsername;
    @Value("${BING_ADS_PASSWORD}")
    private String bingAdsPassword;
    @Value("${BING_ADS_REFRESH_TOKEN}")
    private String bingAdsRefreshToken;
    @Bean
    public OAuthDesktopMobileAuthCodeGrant oAuthWebAuthCodeGrant() throws MalformedURLException {
        OAuthDesktopMobileAuthCodeGrant oAuthWebAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(bingAdsClientId, bingAdsRefreshToken);
        return oAuthWebAuthCodeGrant;
    }
    @Bean
    public AuthorizationData authorizationData(OAuthDesktopMobileAuthCodeGrant authentication){
        AuthorizationData authorizationData = new AuthorizationData();
        authorizationData.setAuthentication(authentication);
        authorizationData.setCustomerId(new Long(bingAdsCustomerId));
        authorizationData.setAccountId(new Long(bingAdsAccountId));
        authorizationData.setDeveloperToken(bingAdsDeveloperToken);
        return authorizationData;
    }
    @Bean
    public BulkServiceManager bulkServiceManager(AuthorizationData authorizationData){
        BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);
        bulkServiceManager.setStatusPollIntervalInMilliseconds(5000);
        return bulkServiceManager;
    }
}

Step 2: Setup Bing Adwords Service

package com.integration.adwords.service;
import com.microsoft.bingads.AuthorizationData;
import com.microsoft.bingads.bulk.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
/**
 * Created by tmichels on 7/31/15.
 */
@Service
public class BingAdwordService {
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(BingAdwordService.class);
    private static final String OUTPUTFILENAME="bingAdwords.csv";
    private static final String FILEDIRECTORY="adwords/bing/";
    @Autowired
    BulkServiceManager bulkService;
    public void submitAndDownloadWithBulkServiceManager() throws IOException, URISyntaxException {
        try {
            logger.info("Start BingAdwordService submitAndDownloadWithBulkServiceManager");
            SubmitDownloadParameters submitDownloadParameters = new SubmitDownloadParameters();
            submitDownloadParameters.setCampaignIds(null);
            ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
            dataScope.add(DataScope.ENTITY_DATA);
            submitDownloadParameters.setDataScope(dataScope);
            submitDownloadParameters.setFileType(DownloadFileType.CSV);
            submitDownloadParameters.setLastSyncTimeInUTC(null);
            ArrayList<BulkDownloadEntity> bulkDownloadEntities = new ArrayList<BulkDownloadEntity>();
            bulkDownloadEntities.add(BulkDownloadEntity.CAMPAIGNS);
            bulkDownloadEntities.add(BulkDownloadEntity.AD_GROUPS);
            bulkDownloadEntities.add(BulkDownloadEntity.KEYWORDS);
            bulkDownloadEntities.add(BulkDownloadEntity.ADS);
            submitDownloadParameters.setEntities(bulkDownloadEntities);
            BulkDownloadOperation bulkDownloadOperation = bulkService.submitDownloadAsync(submitDownloadParameters, null).get();
            BulkOperationStatus<DownloadStatus> downloadStatus;
            int waitTime = 5000;
            for (int i = 0; i < 24; i++) {
                Thread.sleep(waitTime);
                downloadStatus = bulkDownloadOperation.getStatusAsync(null).get();
                if (downloadStatus.getStatus() == DownloadStatus.COMPLETED) {
                    break;
                }
            }
            File resultFile = bulkDownloadOperation.downloadResultFileAsync(
                    new File(FILEDIRECTORY),
                    OUTPUTFILENAME,
                    true,
                    true,  // Set this value true if you want to overwrite the same file.
                    null).get();
            logger.info("Download BingAdwords file success %s\n", resultFile.getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Leave a Reply

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

Gravatar
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 )

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

Connecting to %s