How to get Google Ads impressions based on location - java

I am working with Google Ads API. Based on my use case, I need to get the impressions, clicks, and other statistics about the products based on location(Without creating the campaign).
I contacted the Google Ads API team to address the issue but the doc reference they provided me didn't work in my case. (I'm not using keywords also)
generate forecast metrics
And also the query I used to access the data is...
public void queryTest(long customerId,String campaignId) {
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
SearchGoogleAdsStreamRequest request =
SearchGoogleAdsStreamRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setQuery("SELECT metrics.clicks, metrics.impressions,geographic_view.country_criterion_id FROM geographic_view WHERE geographic_view.country_criterion_id = 1009919")
.build();
ServerStream<SearchGoogleAdsStreamResponse> stream =
googleAdsServiceClient.searchStreamCallable().call(request);
for (SearchGoogleAdsStreamResponse response : stream) {
for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
System.out.println("outPut"+googleAdsRow.getGeographicView());
}
}
}
}
Can someone please help me to resolve this issue??
Thank you!!

Related

OSPermissionSubscriptionState : Cannot resolve symbol

I'm trying to add push notification to my mobile native chat app. I'm trying to use OneSignal.
I can send manual push notification, so I think gradle part is okay
idsAvaiable method is deprecated, I started to looking for how can I get userId.
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
String userId = status.getSubscriptionStatus().getUserId();
In here, I'm trying to get userId with status, but it's saying:
Cannot resolve symbol 'OSPermissionSubscriptionState'
How can I get userId?
Root cause
From OneSignal API 4.0.0, there are many APIs that have been removed including OSPermissionSubscriptionState.
Solution 1
Use OneSignal.getDeviceState()
OSDeviceState device = OneSignal.getDeviceState();
String userId = device.getUserId();
Solution 2
Use OneSignal.addSubscriptionObserver()
OneSignal.addSubscriptionObserver(new OSSubscriptionObserver() {
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().isSubscribed() && stateChanges.getTo().isSubscribed()) {
// Get user id
String userId = stateChanges.getTo().getUserId();
}
}
});
For more information, see the change log here.

Facebook marketing API custom website audience targeting using API

I am using Facebook marketing API v2.8 (JAVA preferred)
I am trying to creating custom website audiences using Facebook pixel by using the below rule :
String rule = "{\"url\":{\"eq\":\"http://www.example.com/abc.php\"}}"
public static CustomAudience createWebsitePixelCustomAudience(AdAccount adAccount, String pixelId,
String audienceName, EnumSubtype subtype, String rule) throws
APIException {
CustomAudience customAudience = adAccount.createCustomAudience()
.setPixelId(pixelId)
.setName(audienceName)
.setSubtype(CustomAudience.EnumSubtype.VALUE_WEBSITE)
.setRetentionDays(15L)
.setRule(rule)
.setPrefill(true)
.execute();
return customAudience;
}
What I want to achieve?
I want to target these audiences created above using API (Java preferred).
I tried to do this using this below code by passing Id of custom audiences created above.
public static Targeting targetAudience(List<String> countrylist, String customAudienceID) {
TargetingGeoLocation geoLocation = new TargetingGeoLocation()
.setFieldCountries(countrylist);
Targeting targeting = new Targeting()
.setFieldGeoLocations(geoLocation)
.setFieldCustomAudiences(customAudienceID);
return targeting;
}
I used the customAudienceID that I created at the start and passed it to above function.
But I am getting this error : Expected BEGIN_ARRAY but was NUMBER at line 1 column 14 path
Is this the correct way of linking custom website audience to AdSet?
Thanks ?
Finally I find a way to do it :
public static Targeting targetCustomAudience(List<String> countrylist, String customAudienceID) {
TargetingGeoLocation geoLocation = new TargetingGeoLocation()
.setFieldCountries(countrylist);
/**
* add geo-location to targeting
* add custom audienceId to targeting
*/
Targeting targeting = new Targeting()
.setFieldGeoLocations(geoLocation)
.setFieldCustomAudiences("[{id:" + customAudienceID + "}]");
return targeting;
}
Thanks to this link
In short add this line "[{id:" + customAudienceID + "}]" to add custom audience to targeting.

How to pull more than 500 user objects from my domain?

I am trying to pull about 20,000 users from my Google domain. However, i know that Google only has a limit of about 500 users for a pull request. I know about the pageToken stuff, but the documentation for it online is terrible. Can someone show me how to use the pageToken? Please keep in mind i am using the google client libraries. This is what my code looks like so far:
#Test
public void paginationTest() throws IOException, NullPointerException, GeneralSecurityException {
try {
Directory directory = GCAuthentication.getDirectoryService("xxx", "vvv", dddd);
Directory.Users.List list = directory.users().list().setOrderBy("email").setMaxResults(500).setDomain("dev.royallepage.ca");
do {
com.google.api.services.admin.directory.model.Users users = list.execute();
java.util.List<User> uL = users.getUsers();
//uL.addAll(users.getUsers());
//list.setPageToken(list.getPageToken());
System.out.println(uL.size());
}while (list.getPageToken() != null && list.getPageToken().length() > 0);
}catch(NullPointerException e) {
}
}
Please advise what i am doing wrong! Thanks,
Mesam
You will have to create a function that will get the pageToken variable then call another request including the nextPageToken.
Use the pageToken query string for responses with large number of groups. In the case of pagination, the response returns the nextPageToken property which gives a token for the next page of response results. Your next request uses this token as the pageToken query string value.
Sample Code Request:
GET https://www.googleapis.com/admin/directory/v1/users
?domain=primary domain name&pageToken=token for next results page
&maxResults=max number of results per page
&orderBy=email, givenName, or familyName
&sortOrder=ascending or descending
&query=email, givenName, or familyName:the query's value*
Hope this helps!

View all comments on a YouTube video

I am trying to get all the comments on a YouTube video using a Java program. I cannot get them though as it has the "Show More" instead of all the comments. I'm looking for a way to get all the comments or pages of comments that I can go through. I have a video id and things, just need the comments.
I have tried all_comments instead of watch in the URL but it doesn't show all comments still and redirects to watch again.
I have also looked at the YouTube api and can only find how to get comments with their id but I need to get all comments from a video id.
If anyone knows how to do this please tell me.
I have added a 50 rep bounty for whoever can give me a good answer to this.
You need to get comment threads list request for your video and then scroll forward using next page token from the last response:
private static int counter = 0;
private static YouTube youtube;
public static void main(String[] args) throws Exception {
// For Auth details consider:
// https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/Auth.java
// Also don't forget secrets https://github.com/youtube/api-samples/blob/master/java/src/main/resources/client_secrets.json
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
Credential credential = Auth.authorize(scopes, "commentthreads");
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build();
String videoId = "video_id";
// Get video comments threads
CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute();
while (true) {
handleCommentsThreads(commentsPage.getItems());
String nextPageToken = commentsPage.getNextPageToken();
if (nextPageToken == null)
break;
// Get next page of video comments threads
commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute();
}
System.out.println("Total: " + counter);
}
private static YouTube.CommentThreads.List prepareListRequest(String videoId) throws Exception {
return youtube.commentThreads()
.list("snippet,replies")
.setVideoId(videoId)
.setMaxResults(100L)
.setModerationStatus("published")
.setTextFormat("plainText");
}
private static void handleCommentsThreads(List<CommentThread> commentThreads) {
for (CommentThread commentThread : commentThreads) {
List<Comment> comments = Lists.newArrayList();
comments.add(commentThread.getSnippet().getTopLevelComment());
CommentThreadReplies replies = commentThread.getReplies();
if (replies != null)
comments.addAll(replies.getComments());
System.out.println("Found " + comments.size() + " comments.");
// Do your comments logic here
counter += comments.size();
}
}
Consider api-samples, if you need a sample skeleton project.
Update
The situation when you can't get all the comments can be also caused by the quota limits (at least I faced it):
units/day 50,000,000
units/100seconds/user 300,000
This is not a java, python, js, or whatever language specific rules. If you want to get above the quota, you cant try to apply for higher quota. Though, I would start from controlling your throughput. It's very easy to get above the 100seconds/user quota.
try this it can download all the comments for a given video which i have tested.
https://github.com/egbertbouman/youtube-comment-downloader
python downloader.py --youtubeid YcZkCnPs45s --output OUT
Downloading Youtube comments for video: YcZkCnPs45s
Downloaded 1170 comment(s)
Done!
output is in the JSON format:
{
"text": "+Tony Northrup many thanks for the prompt reply - I'll try that.",
"time": "1 day ago",
"cid": "z13nfbog0ovqyntk322txzjamuensvpch.1455717946638546"
}

Accessing Books API through AppEngine fails with error code 400

I'm getting following error when accessing Google Books APIs from Google AppEngine Application.
API key for server application is used.
But if you run application locally in eclipse there is no problem.
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Cannot determine user location for geographically restricted operation.",
"reason" : "unknownLocation"
} ],
"message" : "Cannot determine user location for geographically restricted operation."
}
There is not enough information on this error scenario.
Any help is appreciated. Thanks.
Well, this may be because the IP cannot be used to locate the user. It makes sense looking at the error message and with some googling here:
https://productforums.google.com/forum/#!topic/books-api/88Ml3YIpvLw
Try adding &country=GB to the end of the request, or whichever 2 letter represent the country which you are wanting to search from. (More here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)
This answer is mainly from the answer in the given link, however it appears to work and took some looking for. I hope it helps.
This following code solved my problem using Google Books API itself.
///////////////////////////////////////////////////
UrlFetchTransport url = new UrlFetchTransport();
final Books books = new Books.Builder(
url, jsonFactory, null)
.setApplicationName(APPLICATION_NAME)
.setGoogleClientRequestInitializer(
new GBookRequest()).build();
List volumesList = books.volumes().list("isbn:9780199562855");
// Execute the query.
Volumes volumes = volumesList.execute();
if (volumes.getTotalItems() == 0 || volumes.getItems() == null) {
log.info("No matches found in GBooks.");
return null;
}
///////////////////////////////////////////////////
public class GBookRequest extends BooksRequestInitializer {
private static String apiKey = "xxxxxx";
public GBookRequest() {
super(apiKey);
}
#Override
public void initializeBooksRequest(BooksRequest request)
throws IOException {
request.set("country", "US");
}
}
///////////////////////////////////////////////////

Categories

Resources