// This example assumes that you are using Axis 1.4 and
// the Xerxes parser. Additionally, it requires
// pre-compiling the proxy classes by using wsdl2java.
// If you are using a different environment, update it as needed.
// Application-specific name of package.
// If you place this code in a package, invoke the code
// at the command line by typing
// java java_adCenter.MyReport
// along with the parameters used for the credentials and developer token.
// If you choose to not place this code in a package, invoke the code
// at the command line by typing
// java MyReport
// along with the parameters used for the credentials and developer token.
package java_adCenter;
import java.io.*;
import java.util.*;
import java.net.URL;
import com.microsoft.adapi.*;
import com.microsoft.adcenter.v6.*;
public class MyReport
{
public static void main(String[] args)
{
String reportId = null;
int[] accountIds = { 489 }; // Application-specific value.
int waitMinutes = 15;
int maxWaitMinutes = 120;
int elapsedMinutes = 0;
// The Microsoft adCenter API namespace,
// which is used in the SOAP header.
String namespace =
"https://adcenter.microsoft.com/v6";
// This example URL is for the sandbox environment.
// Update the URL as needed when using the production environment.
String url = "https://sandboxapi.adcenter.microsoft.com/Api/Advertiser/v6/Reporting/ReportingService.svc?wsdl";
// The following is the production environment URL.
// String url = "https://adcenterapi.microsoft.com/Api/Advertiser/v6/Reporting/ReportingService.svc?wsdl";
IReportingService reportManagement = null;
ReportingServiceLocator reportServiceLocator = null;
BasicHttpBinding_IReportingServiceStub stub = null;
SubmitGenerateReportRequest submitGenerateReportRequest = null;
SubmitGenerateReportResponse submitGenerateReportResponse = null;
PollGenerateReportRequest pollGenerateReportRequest = null;
PollGenerateReportResponse pollGenerateReportResponse = null;
ReportRequestStatus reportRequestStatus = null;
ReportRequestStatusType status = null;
try
{
if (args.length != 3)
{
// This application expects the user name, password, and
// developer token to be passed in as command-line arguments.
System.out.println("Correct usage:");
System.out.print("java MyReport ");
System.out.println("user_name password developertoken");
System.exit(-1);
}
reportServiceLocator = new
ReportingServiceLocator();
reportServiceLocator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
reportManagement =
reportServiceLocator.getBasicHttpBinding_IReportingService();
stub = (BasicHttpBinding_IReportingServiceStub)
reportManagement;
// Assign values for the credentials and the developer token.
// args[0] is the user name.
// args[1] is the password.
// args[2] is the developer token.
// The application token is reserved for future use and
// does not need to be assigned a value.
stub.setHeader(namespace,
"ApplicationToken", "");
stub.setHeader(namespace,
"DeveloperToken", args[2]);
stub.setHeader(namespace,
"UserName", args[0]);
stub.setHeader(namespace,
"Password", args[1]);
stub.setHeader(namespace,
"CustomerAccountId", "");
KeywordPerformanceReportRequest reportRequest =
new KeywordPerformanceReportRequest();
// Specify the language of the report.
reportRequest.setLanguage(ReportLanguage.English);
// Specify the format of the report.
reportRequest.setFormat(ReportFormat.Xml);
reportRequest.setReturnOnlyCompleteData(false);
reportRequest.setReportName("My Keyword Report");
reportRequest.setAggregation(ReportAggregation.Monthly);
// Specify the time frame of the report.
ReportTime reportTime=new ReportTime();
reportTime.setPredefinedTime(ReportTimePeriod.LastSixMonths);
reportTime.setCustomDates(null);
reportTime.setCustomDateRangeStart(null);
reportTime.setCustomDateRangeEnd(null);
reportRequest.setTime(reportTime);
// Specify the scope of the report. This example goes
// only to the account level, but you can request a report
// for any number of accounts, ad groups, and campaigns.
AccountThroughAdGroupReportScope scope =
new AccountThroughAdGroupReportScope();
scope.setAccountIds(accountIds);
reportRequest.setScope(scope);
// Specify the filter for the report. The report request
// in this example specifies only the search ads that were
// displayed in the United States.
KeywordPerformanceReportFilter filter =
new KeywordPerformanceReportFilter();
String[] adDist = { "Search" };
filter.setAdDistribution(adDist);
String[] langAndRegion = { "UnitedStates" };
filter.setLanguageAndRegion(langAndRegion);
filter.setDeliveredMatchType(null);
filter.setKeywords(null);
reportRequest.setFilter(filter);
// Specify the columns that will be in the report.
KeywordPerformanceReportColumn[] columns;
columns = new KeywordPerformanceReportColumn[6];
columns[0] = KeywordPerformanceReportColumn.AccountName;
columns[1] = KeywordPerformanceReportColumn.CampaignName;
columns[2] = KeywordPerformanceReportColumn.Keyword;
columns[3] = KeywordPerformanceReportColumn.TimePeriod;
columns[4] = KeywordPerformanceReportColumn.Impressions;
columns[5] = KeywordPerformanceReportColumn.Conversions;
reportRequest.setColumns(columns);
// Create the service operation request object, and then assign values.
submitGenerateReportRequest = new SubmitGenerateReportRequest();
submitGenerateReportRequest.setReportRequest(reportRequest);
// Make the call to queue the report.
System.out.println(
"Calling ReportManagement.SubmitGenerateReport");
submitGenerateReportResponse =
reportManagement.submitGenerateReport(submitGenerateReportRequest);
// Display the TrackingId that was returned
// in the response header.
System.out.println("Successful SubmitGenerateReport call.");
System.out.println(
"TrackingId output from response header:");
System.out.println(
stub.getResponseHeader
(
namespace,
"TrackingId")
);
System.out.println(); // A blank line to separate the text
// that follows.
reportId = submitGenerateReportResponse.getReportRequestId();
System.out.print("ReportRequestId: ");
System.out.println(reportId);
// Poll to get the status of the report until it is complete.
do
{
// Wait the specified number of minutes before you poll.
System.out.print(String.format(
"Waiting another %d minutes. ",
waitMinutes));
System.out.println(String.format(
"Total wait time so far is %d minutes.",
elapsedMinutes));
Thread.sleep(waitMinutes * 60 * 1000);
elapsedMinutes += waitMinutes;
pollGenerateReportRequest = new PollGenerateReportRequest();
pollGenerateReportRequest.setReportRequestId(reportId);
// Make the call to get the report status.
System.out.println(
"Calling ReportManagement.pollGenerateReportRequest");
pollGenerateReportResponse =
reportManagement.pollGenerateReport(pollGenerateReportRequest);
// Display the TrackingId that was returned
// in the response header.
System.out.println("Successful PollGenerateReport call.");
System.out.println(
"TrackingId output from response header:");
System.out.println(
stub.getResponseHeader
(
namespace,
"TrackingId")
);
reportRequestStatus =
pollGenerateReportResponse.getReportRequestStatus();
status = reportRequestStatus.getStatus();
// If the report was created, download it.
if (ReportRequestStatusType.Success == status)
{
String fileName = null;
String downloadURLString = null;
URL downloadUrl = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
int count = 0;
fileName = reportId + ".zip";
// Open a connection to the URL where
// the report is available.
downloadURLString =
reportRequestStatus.getReportDownloadUrl();
downloadUrl = new URL(downloadURLString);
inputStream = downloadUrl.openStream();
// Open the report file.
fileOutputStream = new FileOutputStream(fileName);
// Read the report data.
while (-1 != (count = inputStream.read()))
{
// Write the report data to the file.
fileOutputStream.write(count);
}
// Flush and close the file.
fileOutputStream.flush();
fileOutputStream.close();
System.out.println(String.format(
"The report named %s was successfully downloaded.",
fileName));
break;
}
else if (ReportRequestStatusType.Pending == status)
{
// The report is not yet ready.
continue;
}
else
{
// An error occurred.
throw new Exception(status.toString());
}
} while (elapsedMinutes < maxWaitMinutes);
}
// Exception handling.
catch (ApiFaultDetail fault)
{
System.out.println("ApiFaultDetail exception encountered.");
System.out.println(String.format("Tracking ID: %s",
fault.getTrackingId()));
// Display service operation error information.
for (int i = 0; i < fault.getOperationErrors().length; i++)
{
System.out.println("Operation error encountered:");
System.out.println(String.format("\tMessage: %s",
fault.getOperationErrors()[i].getMessage()));
System.out.println(String.format("\tDetails: %s",
fault.getOperationErrors()[i].getDetails()));
System.out.println(String.format("\tErrorCode: %s",
fault.getOperationErrors()[i].getErrorCode()));
System.out.println(String.format("\tCode: %s",
fault.getOperationErrors()[i].getCode()));
}
// Display batch error information.
for (int i = 0; i < fault.getBatchErrors().length; i++)
{
System.out.println(String.format("Batch error encountered for array index %s.",
fault.getBatchErrors()[i].getIndex()));
System.out.println(String.format("\tMessage: %s",
fault.getBatchErrors()[i].getMessage()));
System.out.println(String.format("\tDetails: %s",
fault.getBatchErrors()[i].getDetails()));
System.out.println(String.format("\tErrorCode: %s",
fault.getBatchErrors()[i].getErrorCode()));
System.out.println(String.format("\tCode: %s",
fault.getBatchErrors()[i].getCode()));
}
// Exit the application or take other action.
System.exit(-1);
}
catch (AdApiFaultDetail fault)
{
System.out.println("AdApiFaultDetail exception encountered.");
System.out.println(String.format("Tracking ID: %s",
fault.getTrackingId()));
// Display API error information.
for (int i = 0; i < fault.getErrors().length; i++)
{
System.out.println("Error encountered:");
System.out.println(String.format("\tMessage: %s",
fault.getErrors()[i].getMessage()));
System.out.println(String.format("\tDetail: %s",
fault.getErrors()[i].getDetail()));
System.out.println(String.format("\tErrorCode: %s",
fault.getErrors()[i].getErrorCode()));
System.out.println(String.format("\tCode: %s",
fault.getErrors()[i].getCode()));
}
// Exit the application or take other action.
System.exit(-1);
}
// Capture exceptions on the client that are unrelated to
// the adCenter API.
catch (Exception e)
{
System.out.print("Error encountered: ");
e.printStackTrace();
// Exit the application or take other action.
System.exit(-1);
}
}
}