Thursday, 24 November 2016

Re: Frequently getting Stream closed error whe fetching ads for a Adgroup and for a given campaign

package com.ntrs.ppc.googleAds;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.sql.ClientInfoStatus;
import java.util.ArrayList;
import java.util.List;

import org.mockito.asm.tree.IntInsnNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201607.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201603.cm.ReportDefinitionService;
import com.google.api.ads.adwords.axis.v201603.mcm.ManagedCustomerService;
import com.google.api.ads.adwords.axis.v201603.mcm.ManagedCustomerServiceError;
import com.google.api.ads.adwords.axis.v201607.cm.Ad;
import com.google.api.ads.adwords.axis.v201607.cm.AdCustomizerFeedServiceInterface;
import com.google.api.ads.adwords.axis.v201607.cm.AdGroup;
import com.google.api.ads.adwords.axis.v201607.cm.AdGroupAd;
import com.google.api.ads.adwords.axis.v201607.cm.AdGroupAdPage;
import com.google.api.ads.adwords.axis.v201607.cm.AdGroupAdServiceInterface;
import com.google.api.ads.adwords.axis.v201607.cm.AdGroupPage;
import com.google.api.ads.adwords.axis.v201607.cm.AdGroupServiceInterface;
import com.google.api.ads.adwords.axis.v201607.cm.Campaign;
import com.google.api.ads.adwords.axis.v201607.cm.CampaignPage;
import com.google.api.ads.adwords.axis.v201607.cm.CampaignServiceInterface;
import com.google.api.ads.adwords.axis.v201607.cm.ExpandedTextAd;
import com.google.api.ads.adwords.axis.v201607.cm.Predicate;
import com.google.api.ads.adwords.axis.v201607.cm.PredicateOperator;
import com.google.api.ads.adwords.axis.v201607.cm.ReportDefinitionReportType;
import com.google.api.ads.adwords.axis.v201607.cm.Selector;
import com.google.api.ads.adwords.axis.v201607.cm.TextAd;
import com.google.api.ads.adwords.axis.v201607.mcm.ManagedCustomer;
import com.google.api.ads.adwords.axis.v201607.mcm.ManagedCustomerPage;
import com.google.api.ads.adwords.axis.v201607.mcm.ManagedCustomerServiceInterface;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration;
import com.google.api.ads.adwords.lib.jaxb.v201607.DownloadFormat;
import com.google.api.ads.adwords.lib.jaxb.v201607.ReportDefinition;
import com.google.api.ads.adwords.lib.selectorfields.v201607.cm.AccountLabelField;
import com.google.api.ads.adwords.lib.selectorfields.v201607.cm.AdGroupAdField;
import com.google.api.ads.adwords.lib.selectorfields.v201607.cm.AdGroupField;
import com.google.api.ads.adwords.lib.selectorfields.v201607.cm.CampaignField;
import com.google.api.ads.adwords.lib.selectorfields.v201607.cm.CustomerFeedField;
import com.google.api.ads.adwords.lib.selectorfields.v201607.cm.ManagedCustomerField;
import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;
import com.google.api.ads.adwords.lib.utils.v201607.ReportDownloader;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.services.analyticsreporting.v4.model.Report;


@Component
public class GoogleAdsServiceImpl implements GoogleAdsServiceInter {


@Value("${GOOGLE.ADWORDS.KEY_FILE}")
private String KEY_FILE_LOCATION ;


@Value("${GOOGLE.ADWORDS.CLIENT_ID}")
private String clientId ;

@Value("${GOOGLE.ADWORDS.CLIENT_SECRET}")
private String clientSecret ;

@Value("${GOOGLE.ADWORDS.REFRESH_TOKEN}")
private String refreshToken ;
@Value("${GOOGLE.ADWORDS.DEVELOPER_TOKEN}")
private String developerToken ;

@Value("${GOOGLE.ADWORDS.CLIENT_CUSTOMERID}")
private String clientCustomerId ;

@Value("${GOOGLE.ADWORDS.PAGE_SIZE}")
private int PAGE_SIZE ;

//int PAGE_SIZE=Integer.parseInt(pageSize);



//public static String KEY_FILE_LOCATION ="C://Users//rm386//share//WrkngDir//workspace//MDC//src//main//resources//ads.properties";



/*public static void main(String[] args) {
GoogleAdsServiceImpl impl = new GoogleAdsServiceImpl();
AdWordsServices adWordsServices = new AdWordsServices();
String contextpath=KEY_FILE_LOCATION;
AdWordsSession session = impl.intiateSession(contextpath);
System.out.println("After initializing ");

AccountPojo accpojo=new AccountPojo();
accpojo.setClientId(clientId);
accpojo.setCampaign(impl.getCampaigns(adWordsServices, session));
System.out.println("pojo is ");
System.out.println(accpojo);
}*/

@Override
public AdWordsSession intiateSession(String contextpath,String accountNum) {
try {

/*Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https-proxy", 443));
Proxy proxy1 = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https-proxy", 80));
//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("auth-proxy.ntrs.com", 3128));
HttpTransport httpTransport = new NetHttpTransport.Builder().setProxy(proxy).build();
HttpTransport httpTransport1 = new NetHttpTransport.Builder().setProxy(proxy1).build();
*/
String keyfile=contextpath+KEY_FILE_LOCATION;

System.setProperty("https.proxyHost", "auth-proxy.ntrs.com");
System.setProperty("https.proxyPort", "3128");
// Get an OAuth2 credential.
Credential credential = new OfflineCredentials.Builder()
.forApi(OfflineCredentials.Api.ADWORDS)
.fromFile(keyfile)
.build()
.generateCredential();

// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
.fromFile(keyfile)
.withOAuth2Credential(credential)
.build();

/**
* Alternatively, you can specify your credentials in the constructor:
*/

/* // Get an OAuth2 credential.
Credential credential = new OfflineCredentials.Builder()
.forApi(OfflineCredentials.Api.ADWORDS)
.withClientSecrets(clientId, clientSecret)
.withRefreshToken(refreshToken)
.build()
.generateCredential();

// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
.withDeveloperToken(developerToken).withClientCustomerId(clientCustomerId)
.withOAuth2Credential(credential)
.build();
*/


// session.setClientCustomerId(clientCustomerId);
return session;

}
catch(Exception e){
e.printStackTrace();
return null;
}
}

@Override
public List<CampaignPojo> getCampaigns(AdWordsServices adWordsServices, AdWordsSession session,String contextpath) {
// Get the CampaignService.
String[]details=contextpath.split("@");
String accNum=details[1];
contextpath=details[0];
CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
CampaignPojo camppojo=new CampaignPojo();
List<CampaignPojo> cpojo=new ArrayList<CampaignPojo>();
int offset = 0;

/* Predicate predicate = new Predicate();
predicate.setField("CampaignId");
predicate.setOperator(PredicateOperator.EQUALS);
predicate.setValues(new String[]{accNum});*/


// Create selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields(CampaignField.Id, CampaignField.Name, CampaignField.Status, CampaignField.CampaignTrialType)
//.equals(ManagedCustomer .Id, "702560288")
.orderAscBy(CampaignField.Name)
.offset(offset)
.limit(PAGE_SIZE)
.build();

CampaignPage page = null;
int i=0;
boolean readMore = true;
do {
// Get all campaigns.
try {
page = campaignService.get(selector);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("No. of campaigns "+page.getEntries().length );
// Display campaigns.
if (page.getEntries() != null) {
System.out.println("campaigns length for account "+page.getEntries().length);
for (Campaign campaign : page.getEntries()) {
i=i+1;
camppojo=new CampaignPojo();
/*if(i==10)
break;*/



Long campaignId = campaign.getId();
camppojo.setCampaignId(String.valueOf(campaignId));
System.out.println("Campaign-------------------------"+ campaignId);
camppojo.setCampaignName(campaign.getName());
//System.out.println(" campauign statuis is "+campaign.getStatus().toString());//return type is campaignStatus
camppojo.setCampaignStatus(campaign.getStatus().toString());
// System.out.println(" Capign Trial Type "+campaign.getCampaignTrialType().toString());//return type is campaignTrialType
camppojo.setCampaignTrailType(campaign.getCampaignTrialType().toString());
AdWordsServices adWordsServicesAdGroup = new AdWordsServices();
List<AdGroupPojo> adGroup =getAdsUsingCampaigns(adWordsServicesAdGroup, session, campaignId,contextpath);
camppojo.setAdGroup(adGroup);
cpojo.add(camppojo);
}
} else {
System.out.println("No campaigns were found.");
readMore = false;
}

offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
//offset= page.getTotalNumEntries()+1;
} while (readMore/*offset < page.getTotalNumEntries()*/);
return cpojo;
}

@Override
public List<AdGroupPojo> getAdsUsingCampaigns(AdWordsServices adWordsServices, AdWordsSession session, Long campaignId,String contextpath) {
// Get the AdGroupService.
AdGroupServiceInterface adGroupService =adWordsServices.get(session, AdGroupServiceInterface.class);

List<AdGroupPojo> adGrouplst =new ArrayList<AdGroupPojo>();
AdGroupPojo adgrppojo=new AdGroupPojo();
AdsParamPojo adparampojo=new AdsParamPojo();
int offset = 0;
boolean morePages = true;

// Create selector.
SelectorBuilder builder = new SelectorBuilder();

Selector selector = builder
// .fields(strArr)
.fields(
AdGroupAdField.Id,
AdGroupAdField.Status,
AdGroupField.Name)
.orderAscBy(AdGroupField.Name)
.offset(offset)
.limit(PAGE_SIZE)
.equals(AdGroupField.CampaignId, String.valueOf(campaignId))
//.equals(AdGroupAdField.Id,"40347979127")
//.equals("AdType", "EXPANDED_TEXT_AD")
// .forDateRange(start, end)
.build();

int i=0;
// while (morePages) {
// Get all ad groups.
AdGroupPage page =null;
do{
try {
page = adGroupService.get(selector);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("No. of adgroups "+page.getEntries() );
// Display ad groups.
if (page.getEntries() != null) {
for (AdGroup adGroup : page.getEntries()) {
/*if(i==5)
break;*/
adgrppojo=new AdGroupPojo();
System.out.println("Ads Group ---------------------------"+ adGroup.getId() +"------" +
adGroup.getStatus() +"----"+ adGroup.getName() + "--Count---->"+i);
adgrppojo.setAdGroupId(String.valueOf(adGroup.getId()));
adgrppojo.setAdGroupName(adGroup.getName());
adgrppojo.setAdGroupStatus(adGroup.getStatus().getValue());//return type is AdGroup need to check
//adgrppojo.setKeyword(keyword);
adparampojo=new AdsParamPojo();
adparampojo.setCampaignId(campaignId);
// adparampojo.setCampaignId(campaignId);

adparampojo.setAdgroupId(adGroup.getId());

adparampojo.setContextPath(contextpath);
AdWordsServices adWordsServicesAdGroupAd = new AdWordsServices();
List<AdsPojo> ads= getAd(adWordsServicesAdGroupAd, session, adparampojo);
adgrppojo.setAd(ads);
adGrouplst.add(adgrppojo);i++;
}
} else {
System.out.println("No ad groups were found.");
}

offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
//offset= page.getTotalNumEntries()+1;

} while (offset < page.getTotalNumEntries());
return adGrouplst;
}

/*@Override
public List<AdsPojo> getAd(AdWordsServices adWordsServices, AdWordsSession session, Long adGroupId){
AdGroupAdServiceInterface agas = adWordsServices.get(session, AdGroupAdServiceInterface.class);

List<AdsPojo> adspojo=new ArrayList<AdsPojo>();
AdsPojo adpojo=new AdsPojo();
int offset = 0;
boolean morePages = true;

// Create selector.
SelectorBuilder builder = new SelectorBuilder();
ReportDefinition r=new ReportDefinition();
r.getSelector();
Selector selector = builder
.fields(
AdGroupAdField.Id,
AdGroupAdField.Status,
AdGroupField.Name)
.offset(offset)
.limit(PAGE_SIZE)
.equals(AdGroupField.BaseAdGroupId, adGroupId.toString())
// .forDateRange(start, end)
.build();


// String query = "SELECT CampaignId, AdGroupId, Impressions, Clicks, Cost FROM ADGROUP_PERFORMANCE_REPORT WHERE AdGroupStatus IN [ENABLED, PAUSED] DURING LAST_7_DAYS";
List<GoogleAdWordsPojo> listAds = new ArrayList<GoogleAdWordsPojo>();
int i=0;
while (morePages) {
// Get all ad groups.
AdGroupAdPage ads = null;
try{
ads=agas.get(selector);//agas.query(selector);
}catch(Exception ex){

}
// Display ad groups.
if (ads.getEntries() != null) {
for (AdGroupAd adGroup : ads.getEntries()) {

Ad adDetails = adGroup.getAd();

ExpandedTextAd eta = null;
TextAd ta = null;
adpojo=new AdsPojo();
GoogleAdWordsPojo gaws= new GoogleAdWordsPojo();
gaws.setCampaignId(adGroup.getBaseCampaignId());
// /adpojo.setAdId(adDetails.getAdType());
adpojo.setAdtype(adDetails.getAdType());
adpojo.setAdId(adDetails.getId().toString());

gaws.setAdGroupId(adGroupId);
gaws.setAdId(adDetails.getId());
String getpathtemp="";//ruchira added
switch (adDetails.getAdType()){
case "ExpandedTextAd":{
eta = (ExpandedTextAd) adDetails;
gaws.setHeadLine1(eta.getHeadlinePart1());
gaws.setHeadLine2(eta.getHeadlinePart2());
gaws.setDescription(eta.getDescription());
gaws.setPath1(eta.getPath1());
gaws.setPath2(eta.getPath2());
getpathtemp=eta.getPath2();

System.out.println("Campaing Id--->"+adGroup.getBaseCampaignId() + "Ad Group Id -->"+adGroup.getBaseAdGroupId()+
" Ad Id -->" +adDetails.getId() +" Ad Head Line1 -->" +eta.getHeadlinePart1()+" Ad HeadLine 2 -->" + eta.getHeadlinePart2()+
"Ad Desc -->"+eta.getDescription() + "--Ad path1" + eta.getPath1() + "--Ad path 2" + eta.getPath2() );
break;
}
case "TextAd":{
ta = (TextAd) adDetails;
gaws.setHeadLine(ta.getHeadline());
gaws.setDescription1(ta.getDescription1());
gaws.setDescription1(ta.getDescription2());
//ruchira added temp code to map getpath
//gaws.setPath2(ta.get);
//ruchria added below code
gaws.setPath2(getpathtemp);

System.out.println("Campaing Id--->"+adGroup.getBaseCampaignId() + "--Ad Group Id -->"+adGroup.getBaseAdGroupId()+
" --Ad Id -->" +adDetails.getId() +" --Ad Head Line1 -->" +ta.getHeadline() + "--Ad Desc -->"+ta.getDescription1() + " --Ad Desc2-->"+ ta.getDescription2());
break;
}
}
listAds.add(gaws);
adspojo.add(adpojo); }
} else {
System.out.println("No ad groups were found.");
}

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



return adspojo;


}*/
@Override
public List<AdsPojo> getAd(AdWordsServices adWordsServices, AdWordsSession session, AdsParamPojo adparampojo){
AdGroupAdServiceInterface agas = adWordsServices.get(session, AdGroupAdServiceInterface.class);

List<AdsPojo> adspojolst=new ArrayList<AdsPojo>();
AdsPojo apojo=new AdsPojo();
List<AdDetails>addetailslst;
BufferedReader br =null;
AdDetails adetails;
int offset = 0;
boolean morePages = true;
ReportingConfiguration reportingConfiguration =
new ReportingConfiguration.Builder()
.skipReportHeader(true)
.skipColumnHeader(false)
.skipReportSummary(true)
// Set to false to exclude rows with zero impressions.
.includeZeroImpressions(true)
.build();
session.setReportingConfiguration(reportingConfiguration);

SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields(
AdGroupAdField.Id,
AdGroupAdField.Status,
AdGroupField.Name)
.offset(offset)
.limit(PAGE_SIZE)
// .equals(AdGroupField.BaseAdGroupId, String.valueOf("38299945642"))
// .equals(AdGroupField.BaseCampaignId, String.valueOf("702264700"))
.equals(AdGroupField.BaseCampaignId, adparampojo.getCampaignId().toString())
.equals(AdGroupField.BaseAdGroupId, adparampojo.getAdgroupId().toString())

// .forDateRange(start, end)
.build();
// Get all ad groups.
AdGroupAdPage ads = null;

try{ do{

ads=agas.get(selector);//agas.query(selector);

int k=0;
System.out.println("ads length "+ads.getEntries().length);
if (ads.getEntries() != null) {
for (AdGroupAd adGroup : ads.getEntries()) {
/*if(k==3)
break;*/



Ad adDetails = adGroup.getAd();
apojo=new AdsPojo();
apojo.setAdId(adDetails.getId().toString());


/*String query = "SELECT Cicks,Impressions,CreativeDestinationUrl,ExternalCustomerId,AdType,Ctr,Cost,CostPerConversion,AverageCpc,AverageCpm,AveragePosition,Engagements,Status,Headline,Device FROM AD_PERFORMANCE_REPORT "+
" where CampaignId="+adparampojo.getCampaignId() +" and AdGroupId="+adparampojo.getAdgroupId()+ " and Id="+adDetails.getId(); //36355213323
*/
String reportFile = adparampojo.getContextPath()+"//test68.csv";
String query = "SELECT Clicks,Impressions,ExternalCustomerId,Ctr,Cost,CostPerConversion,AverageCpc,AverageCpm,AveragePosition,Engagements,Status,Headline,Device FROM AD_PERFORMANCE_REPORT "+
" where CampaignId="+adparampojo.getCampaignId() +" and AdGroupId="+adparampojo.getAdgroupId()+ " and Id="+adDetails.getId(); //36355213323

ReportDownloadResponse response =
new ReportDownloader(session).downloadReport(query, DownloadFormat.CSV);
response.saveToFile(reportFile);
//String responseString = response.getAsString();
// System.out.println(responseString);

String line="";
br = new BufferedReader(new FileReader(reportFile));


// use comma as separator

//String[] responseStringarr = response.getAsString().split("/n");
addetailslst=new ArrayList<AdDetails>();
while (( line = br.readLine()) != null) {
/*for(int arrcnt=0;arrcnt<responseStringarr.length;arrcnt++)
{*/
adetails=new AdDetails();
adetails.setConversionPerClick(line.split(",")[0]);
adetails.setImpressions(line.split(",")[1]);
adetails.setDestinationUrl(adDetails.getUrl());
adetails.setExternalCustomerId(line.split(",")[2]);
adetails.setAdtype(adDetails.getType().getValue());
adetails.setCtr(line.split(",")[3]);
adetails.setCost(line.split(",")[4]);
adetails.setCostPerConversion(line.split(",")[5]);
//AverageCpc,AverageCpm,AveragePosition,Engagements,Status,Headline,Device
adetails.setAvgCpc(line.split(",")[6]);
adetails.setAvgPosition(line.split(",")[7]);
adetails.setEngagements(line.split(",")[8]);
adetails.setStatus(line.split(",")[9]);
adetails.setHeadline(line.split(",")[10]);
adetails.setDevice(line.split(",")[11]);
addetailslst.add(adetails);

}
apojo.setAdDetails(addetailslst);

adspojolst.add(apojo);


}

}



offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
// System.out.println("lisy of add count "+ads.getTotalNumEntries());
} while (offset < ads.getTotalNumEntries());

}catch(Exception ex){
ex.printStackTrace();

}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return adspojolst;

}
@Override
public List<AccountPojo> getPPCXMLDetails() {
List<AccountPojo> accountList = new ArrayList<AccountPojo>();

/*for (int accountLen = 0; accountLen <= 1; accountLen++) {

AccountPojo account = new AccountPojo();
account.setAccountDescriptiveName("Account Desriptive Name");
account.setClientId(clientId);
account.setClinetName("Client Name");
account.setDate("2016-08-13");
account.setPpcService("Google Adwords");

List<CampaignPojo> campaignList = new ArrayList<CampaignPojo>();

for (int campaignLen = 0; campaignLen < 2; campaignLen++) {

CampaignPojo campaignPojo = new CampaignPojo();
campaignPojo.setCampaignId("CampaignId");
campaignPojo.setCampaignName("Campaign Name");
campaignPojo.setCampaignStatus("Campaign Status");
campaignPojo.setCampaignTrailType("campaignTrailType");
campaignList.add(campaignPojo);

List<AdGroupPojo> adGroupList = new ArrayList<AdGroupPojo>();
for (int adGroupId = 0; adGroupId < 2; adGroupId++) {

AdGroupPojo adGroupPojo =new AdGroupPojo();
adGroupPojo.setAdGroupId("AdGroupId");
adGroupPojo.setAdGroupName("Group Name");
adGroupPojo.setAdGroupStatus("Ad Group Status");

List<AdsPojo> adsList = new ArrayList<AdsPojo>();
for (int i = 0; i < 3; i++) {
AdsPojo adsPojo = new AdsPojo();
adsPojo.setAdId("Ad Id");
adsPojo.setAdtype("Ad Type");
adsPojo.setAvgCpc("AvgCPC");
adsPojo.setAvgCpm("Avg CPM");
adsPojo.setAvgPerSession("Avg Per Session");
adsPojo.setAvgPosition("Avg Position");
adsPojo.setAvgPost("Avg Post");
adsPojo.setBounceRate("Bounce Rate");
adsPojo.setClicks("Clicks");
adsPojo.setConversionPerClick("conversionPerClick");
adsPojo.setConversions("conversions");
adsPojo.setCost("cost");
adsPojo.setCostPerConversion("costPerConversion");
adsPojo.setCpc("cpc");
adsPojo.setCtr("ctr");
adsPojo.setDestinationUrl("destination URL");
adsPojo.setDevice("device");
adsPojo.setEngagements("engagements");
adsPojo.setImpressions("impressions");
adsPojo.setMaxCpc("maxCpc");
adsPojo.setPagePerVisit("pagePerVisit");
adsPojo.setRegion("region");
adsPojo.setSession("session");
adsPojo.setState("state");
adsList.add(adsPojo);
}

adGroupPojo.setAd(adsList);

List<KeywordsPojo> keywordsList = new ArrayList<KeywordsPojo>();
for (int keywordsLen = 0; keywordsLen < 2 ;keywordsLen++) {
KeywordsPojo keywords = new KeywordsPojo();
keywords.setKeyword("Keyword");
keywords.setKeywordId("keywordId");
keywords.setKeywordMatchType("keywordMatchType");
keywords.setKwywordState("kwywordState");
keywordsList.add(keywords);
}
adGroupPojo.setKeyword(keywordsList);

adGroupList.add(adGroupPojo);
}
campaignPojo.setAdGroup(adGroupList);
campaignList.add(campaignPojo);
}
account.setCampaign(campaignList);
accountList.add(account);
}*/
return accountList;
}

//ruchira begin

@Override
public List<AccountPojo> getPPCGoogleAdwordsDetails() {
List<AccountPojo> accountList = new ArrayList<AccountPojo>();


/*AdWordsSession session =intiateSession(KEY_FILE_LOCATION,"12356");

for (int accountLen = 0; accountLen <= 1; accountLen++) {

AccountPojo account = new AccountPojo();
account.setAccountDescriptiveName("Account Desriptive Name");
account.setClientId(clientId);
account.setClinetName("Client Name");
account.setDate("2016-08-13");
account.setPpcService("Google Adwords");
AdWordsServices adWordsServices = new AdWordsServices();
String conpath="contextoath";
List<CampaignPojo> campaignList = getCampaigns( adWordsServices, session,conpath);
for (int campaignLen = 0; campaignLen < 2; campaignLen++) {

CampaignPojo campaignPojo = new CampaignPojo();
campaignPojo.setCampaignId("CampaignId");
campaignPojo.setCampaignName("Campaign Name");
campaignPojo.setCampaignStatus("Campaign Status");
campaignPojo.setCampaignTrailType("campaignTrailType");
campaignList.add(campaignPojo);

List<AdGroupPojo> adGroupList = new ArrayList<AdGroupPojo>();
for (int adGroupId = 0; adGroupId < 2; adGroupId++) {

AdGroupPojo adGroupPojo =new AdGroupPojo();
adGroupPojo.setAdGroupId("AdGroupId");
adGroupPojo.setAdGroupName("Group Name");
adGroupPojo.setAdGroupStatus("Ad Group Status");

List<AdsPojo> adsList = new ArrayList<AdsPojo>();
for (int i = 0; i < 3; i++) {
AdsPojo adsPojo = new AdsPojo();
adsPojo.setAdId("Ad Id");
adsPojo.setAdtype("Ad Type");
adsPojo.setAvgCpc("AvgCPC");
adsPojo.setAvgCpm("Avg CPM");
adsPojo.setAvgPerSession("Avg Per Session");
adsPojo.setAvgPosition("Avg Position");
adsPojo.setAvgPost("Avg Post");
adsPojo.setBounceRate("Bounce Rate");
adsPojo.setClicks("Clicks");
adsPojo.setConversionPerClick("conversionPerClick");
adsPojo.setConversions("conversions");
adsPojo.setCost("cost");
adsPojo.setCostPerConversion("costPerConversion");
adsPojo.setCpc("cpc");
adsPojo.setCtr("ctr");
adsPojo.setDestinationUrl("destination URL");
adsPojo.setDevice("device");
adsPojo.setEngagements("engagements");
adsPojo.setImpressions("impressions");
adsPojo.setMaxCpc("maxCpc");
adsPojo.setPagePerVisit("pagePerVisit");
adsPojo.setRegion("region");
adsPojo.setSession("session");
adsPojo.setState("state");
adsList.add(adsPojo);
}

adGroupPojo.setAd(adsList);

List<KeywordsPojo> keywordsList = new ArrayList<KeywordsPojo>();
for (int keywordsLen = 0; keywordsLen < 2 ;keywordsLen++) {
KeywordsPojo keywords = new KeywordsPojo();
keywords.setKeyword("Keyword");
keywords.setKeywordId("keywordId");
keywords.setKeywordMatchType("keywordMatchType");
keywords.setKwywordState("kwywordState");
keywordsList.add(keywords);
}
adGroupPojo.setKeyword(keywordsList);

adGroupList.add(adGroupPojo);
}
campaignPojo.setAdGroup(adGroupList);
campaignList.add(campaignPojo);
}
account.setCampaign(campaignList);
accountList.add(account);
}*/
return accountList;
}

@Override
public List<AccountPojo> getListofaccounts(String contextpath) {
// TODO Auto-generated method stub
List<AccountPojo> accountList = new ArrayList<AccountPojo>();

String accountNum;
String keyfile=contextpath+KEY_FILE_LOCATION;
System.setProperty("https.proxyHost", "auth-proxy.ntrs.com");
System.setProperty("https.proxyPort", "3128");
AdWordsServices adWordsServices=new AdWordsServices();
String[]account=clientCustomerId.split("<>");
System.out.println("account>>>>>>>"+account);
System.out.println(CustomerFeedField.FeedId);
try{
for (int accountLen = 0; accountLen <= account.length; accountLen++) {
String acc=account[accountLen];
AdWordsSession session =intiateSession(contextpath,account[accountLen]);
session.setClientCustomerId(acc);
ManagedCustomerServiceInterface managedCustomerService =
adWordsServices.get(session, ManagedCustomerServiceInterface.class);

int offset = 0;
SelectorBuilder selectorBuilder =
new SelectorBuilder()
.fields(ManagedCustomerField.CustomerId, ManagedCustomerField.Name)
// .equals(ManagedCustomerField.CustomerId, acc)
.offset(offset)
.limit(PAGE_SIZE)
;


ManagedCustomerPage page=null;
page = managedCustomerService.get(selectorBuilder.build());
System.out.println("length of account is "+page.getEntries().length);
if (page.getEntries() != null) {
// Create account tree nodes for each customer.
for (ManagedCustomer customer : page.getEntries()) {
AccountPojo accountpojo = new AccountPojo();
accountpojo.setAccountDescriptiveName("Account Desriptive Name");
System.out.println("customer.getCustomerId() "+customer.getCustomerId() +" name "+customer.getName());
accountpojo.setClientId(customer.getCustomerId().toString());
accountpojo.setClinetName(customer.getName());
accountpojo.setDate( customer.getDateTimeZone());
accountpojo.setPpcService("Google Adwords");
contextpath=contextpath+"@"+acc;
accountpojo.setCampaign(getCampaigns(adWordsServices,session,contextpath));
accountList.add(accountpojo);

}
}



}


}
catch(Exception e )
{
}

return accountList;
}

}

Hi,
I have atathced complete code the code start point is getListofAccounts. CustomerId is 429-320-4263
On Wednesday, November 23, 2016 at 11:47:18 AM UTC-6, Shwetha Vastrad (AdWords API Team) wrote:
Hi,

The DownloadCriteriaReport Java example demonstrates how to download a Criteria Performance Report using the API. Could you modify this example to download Ad Performance Report with the fields you require included in the report definition and let me know if this is successful? If it isn't, please provide the complete report definition used along with your clientCustomerId so I can further troubleshoot. 

Regards,
Shwetha, AdWords API Team.

--
--
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
Also find us on our blog and Google+:
https://googleadsdeveloper.blogspot.com/
https://plus.google.com/+GoogleAdsDevelopers/posts
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
 
You received this message because you are subscribed to the Google
Groups "AdWords API Forum" group.
To post to this group, send email to adwords-api@googlegroups.com
To unsubscribe from this group, send email to
adwords-api+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/adwords-api?hl=en
---
You received this message because you are subscribed to the Google Groups "AdWords API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to adwords-api+unsubscribe@googlegroups.com.
Visit this group at https://groups.google.com/group/adwords-api.
To view this discussion on the web visit https://groups.google.com/d/msgid/adwords-api/556a7ab2-b5a9-4220-b54c-7a0208a95b03%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment