Export (0) Print
Expand All

Download Campaigns in Java

The following example shows how to download the entities of one or more campaigns in the background using the following Bulk service operations.

This example has been developed and run within the environment described in Getting Started Using Java with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.


import java.rmi.*;
import java.net.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

import bingads.bulk.*;
import bingads.bulk.adapi.*;

public class DownloadCampaigns {

    private static String namespace = null;
    private static BasicHttpBinding_IBulkServiceStub service = null;

    // Specify your credentials.

    private static String UserName = "<UserNameGoesHere>";
    private static String Password = "<PasswordGoesHere>";
    private static String DeveloperToken = "<DeveloperTokenGoesHere>";
    private static long AccountId = <AccountIdGoesHere>;
    private static long[] CampaignIds = { <CommaSeparatedCampaignIdsGoHere> };

    // The file to download the campaign data to.
    // Because the file is compressed use the .zip file extension.

    private static String DownloadPath = "c:\\bulk\\campaigns.zip";

    // The full path to the previously unzipped download file.
    // This file is used to access the last sync time.

    private static String PreviousDownloadPath = "C:\\bulk\\campaigns\\accounts.xml";


    /**
     * @param args the command line arguments
     *
     *  args[0] - Download ID. If the previous download did not complete in the
     *            allotted time, set args[0] to its download ID to try completing
     *            the download.
     */
    public static void main(String[] args) {
        BulkServiceLocator locator = null;
        GetDownloadStatusResponse response = null;
        String downloadId = null;
        String folder = DownloadPath.substring(0, DownloadPath.lastIndexOf('\\'));
        File dir = new File(folder);

        // Confirm that the download folder exist; otherwise, exit.

        if (!dir.exists())
        {
            System.out.println("The download folder does not exist. Ensure that the " +
                "folder exists and try again.");
            return;
        }

        try
        {
            locator = new BulkServiceLocator();
            namespace = locator.getServiceName().getNamespaceURI();
            service = (BasicHttpBinding_IBulkServiceStub) locator.getBasicHttpBinding_IBulkService();

            // Set the header properties.

            service.clearHeaders();
            service.setHeader(namespace, "CustomerAccountId", AccountId);
            service.setHeader(namespace, "DeveloperToken", DeveloperToken);
            service.setHeader(namespace, "UserName", UserName);
            service.setHeader(namespace, "Password", Password);

            if (args.length == 0)  // Request a new download
            {
                downloadId = RequestDownload(PreviousDownloadPath, AccountId, CampaignIds);
            }
            else  // User passed in the ID of an existing download request.
            {
                downloadId = args[0];
            }

            if (null != downloadId)
            {
                System.out.println("Download ID: " + downloadId);

                response = GetDownloadUrl(downloadId);

                if (null != response)
                {
                    if (response.getStatus().equals(DownloadStatus.Success))
                    {
                        DownloadFile(response.getDownloadUrl(), DownloadPath);
                        System.out.println("The zipped file was written to " + DownloadPath);
                        System.out.println("You will need to uncompress it in order to read it.");
                    }
                    else  // Pending
                    {
                        System.out.println("The request is taking longer than expected.");
                        System.out.printf("Save the report ID (%s) and try again later.", downloadId);
                    }
                }
            }
        }
        catch (RemoteException e)
        {
            System.out.println("Service communication error encountered: ");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        catch (Exception e)
        {
            // Ignore fault exceptions that we already caught.

            if ( e.getCause() instanceof AdApiFaultDetail ||
                 e.getCause() instanceof ApiFaultDetail )
            {
                ;
            }
            else
            {
                System.out.println("Error encountered: ");
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    // Request the download. Use the ID that the request returns to
    // check for the completion of the download.

    private static String RequestDownload(String prevDownloadPath, long accountId, long[] campaignIds) throws RemoteException, Exception
    {
        DownloadCampaignsByCampaignIdsRequest request = new DownloadCampaignsByCampaignIdsRequest();
        
        try
        {
            // Set the request information.

            request.setLastSyncTimeInUTC(GetLastSyncTime(prevDownloadPath));

            request.setAdditionalEntities( new String[] {
                AdditionalEntityNull._AdGroupNegativeKeywords,
                AdditionalEntityNull._AdGroupTargets,
                AdditionalEntityNull._CampaignNegativeKeywords,
                AdditionalEntityNull._CampaignTargets
                }
            );

            ArrayList<CampaignScope> campaigns = new ArrayList<CampaignScope>();

            // The campaigns must all belong to the same account.

            for (long id : campaignIds)
            {
                CampaignScope scope = new CampaignScope();
                scope.setCampaignId(id);
                scope.setParentAccountId(accountId);
                campaigns.add(scope);
            }

            request.setCampaigns(campaigns.toArray(new CampaignScope[0]));

            DownloadCampaignsByCampaignIdsResponse response = service.downloadCampaignsByCampaignIds(request);

            return (response != null) ? response.getDownloadRequestId() : null;
        }
        // Bulk service operations can throw AdApiFaultDetail.
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("The operation failed with the following faults:\n");

            // If the AdApiError array is not null, the following are examples of error codes that may be found.
	    for (AdApiError error : fault.getErrors())
            {
                System.out.printf("AdApiError\n");
                System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", error.getCode(), error.getErrorCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 0:     // InternalError
                        break;
                    case 105:   // InvalidCredentials
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }

            throw new Exception("", fault);
        }
        // Bulk service operations can throw ApiFaultDetail.
        catch (ApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("The operation failed with the following faults:\n");

            // If the BatchError array is not null, the following are examples of error codes that may be found.
            for (BatchError error : fault.getBatchErrors())
            {
                System.out.printf("BatchError at Index: %d\n", error.getIndex());
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 0:     // InternalError
                        break;
                    case 1100:  // CampaignServiceInvalidCampaignId
                        break;
                    case 3203:  // CampaignServiceCampaignsContainsMultipleAccounts
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }

            // If the OperationError array is not null, the following are examples of error codes that may be found.
            for (OperationError error : fault.getOperationErrors())
            {
                System.out.printf("OperationError\n");
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 0:     // InternalError
                        break;
                    case 106:   // UserIsNotAuthorized
                        break;
                    case 1113:  // CampaignServiceCampaignsArrayShouldNotBeNullOrEmpty
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }

            throw new Exception("", fault);
        }
    }

    // Check the status of the download request. The guidance of how often to poll
    // for status is from every five to 15 minutes depending on the amount
    // of data being requested. For smaller requests, you can poll every couple
    // of minutes. You should stop and try polling later if the request
    // is taking longer than an hour.

    private static GetDownloadStatusResponse GetDownloadUrl(String downloadId)  throws RemoteException, Exception
    {
        GetDownloadStatusRequest request = new GetDownloadStatusRequest();
        GetDownloadStatusResponse response = null;
        int waitTime = 1000 * 60 * 1;  // Wait for 1 to 2 minutes for small downloads.

        try
        {
            // Set the request information.

            request.setDownloadRequestId(downloadId);

            // Poll for status up to 12 times (or up to one hour).
            // If the call succeeds, stop polling. If the call or
            // download fails, the call throws a fault.

            for (int i = 0; i < 12; i++)
            {
                try {Thread.sleep(waitTime);}
                catch (InterruptedException ignore) {}

                response = service.getDownloadStatus(request);

                if (response.getStatus().equals(DownloadStatus.Success))
                {
                    break;
                }
            }
        }
        // Bulk service operations can throw AdApiFaultDetail.
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("The operation failed with the following faults:\n");

            // If the AdApiError array is not null, the following are examples of error codes that may be found.
	    for (AdApiError error : fault.getErrors())
            {
                System.out.printf("AdApiError\n");
                System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", error.getCode(), error.getErrorCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 0:     // InternalError
                        break;
                    case 105:   // InvalidCredentials
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }

            throw new Exception("", fault);
        }
        // Bulk service operations can throw ApiFaultDetail.
        catch (ApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("The operation failed with the following faults:\n");

            // If the BatchError array is not null, the following are examples of error codes that may be found.
            for (BatchError error : fault.getBatchErrors())
            {
                System.out.printf("BatchError at Index: %d\n", error.getIndex());
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 0:     // InternalError
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }

            // If the OperationError array is not null, the following are examples of error codes that may be found.
            for (OperationError error : fault.getOperationErrors())
            {
                System.out.printf("OperationError\n");
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());

                switch (error.getCode())
                {
                    case 0:     // InternalError
                        break;
                    case 106:   // UserIsNotAuthorized
                        break;
                    case 3205:  // CampaignServiceInvalidDownloadRequestId
                        break;
                    case 3603:  // CampaignServiceFullSyncRequired
                        break;
                    default:
                        System.out.println("Please see MSDN documentation for more details about the error code output above.");
                        break;
                }
            }

            throw new Exception("", fault);
        }

        return response;
    }

    // Using the URL that the GetDownloadStatus operation returned,
    // send an HTTP request to get the download data and write it
    // to the specified ZIP file.

    private static String DownloadFile(String downloadUrl, String downloadPath) throws IOException
    {
        URL url = new URL(downloadUrl);
        URLConnection request = null;
        int count = 0;
        BufferedInputStream reader = null;
        BufferedOutputStream writer = null;

        try
        {
            request = url.openConnection();

            reader = new BufferedInputStream(request.getInputStream());
            writer = new BufferedOutputStream(new FileOutputStream(downloadPath));

            final int bufferSize = 100 * 1024;
            byte[] buffer = new byte[bufferSize];

            while (-1 != (count = reader.read(buffer, 0, bufferSize)))
            {
                writer.write(buffer, 0, count);
            }
        }
        finally
        {
            reader.close();
            writer.flush();
            writer.close();
        }

        return downloadPath;
    }

    // Get the time stamp of the last download from the previous
    // download file. The SyncTime node contains the time stamp.

    private static Calendar GetLastSyncTime(String path) throws Exception
    {
        Calendar lastSyncTime = null;
        File downloadFile = new File(path);

        if (downloadFile.exists())
        {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream(downloadFile));

            try
            {
                while (reader.hasNext())
                {
                    int eventType = reader.nextTag();

                    if (reader.isStartElement() &&
                        reader.getLocalName().equals("SyncTime"))
                    {
                        String xmlDate = reader.getElementText();

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSSSSS'Z'");
                        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                        lastSyncTime = sdf.getCalendar();
                        lastSyncTime.setTime(sdf.parse(xmlDate));

                        break;
                    }
                }

                if (null  == lastSyncTime)
                {
                    throw new Exception("SyncTime not found in download file " + path + ".");
                }
            }
            finally
            {
                reader.close();
            }
        }

        return lastSyncTime;
    }
}

Community Additions

Show:
© 2015 Microsoft