Google Analytics Report API v4: get Sessions and Revenue data - java

I trying to get Sessions, Revenue, Transactions, Bounce Rate data from Google Analytics Report API v4
with grouping by Chanel:
Organic search
Email
Direct
Branded Paid Search
Social
Referral
.. etc
Right now I'm programming a Java module with test Request which has setted following parameters:
Dimensions:
ga:acquisitionTrafficChannel;
Metrics:
ga:sessions
ga:percentNewSessions
ga:newUsers
When I use ga:acquisitionTrafficChannel + ga:sessions GA Report api returns values, but when I try to add in request ga:percentNewSessions, ga:newUsers, it returns error:
{
"domain": "global",
"message": "Selected dimensions and metrics cannot be queried together.",
"reason": "badRequest"
}
To perform request in code I do following:
DateRange dateRange = new DateRange();
dateRange.setStartDate("2015-06-15");
dateRange.setEndDate("2015-06-30");
ReportRequest request = new ReportRequest()
.setViewId(context.getProperty(VIEW_ID).evaluateAttributeExpressions().getValue())
.setDateRanges(Arrays.asList(dateRange))
.setDimensions(Arrays.asList(
new Dimension().setName("ga:acquisitionTrafficChannel")
))
.setMetrics(Arrays.asList(
new Metric().setExpression("ga:sessions"),
new Metric().setExpression("ga:percentNewSessions"),
new Metric().setExpression("ga:newUsers")
));
ArrayList<ReportRequest> requests = new ArrayList<>();
requests.add(request);
GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);
GetReportsResponse response = service.reports().batchGet(getReport).execute();
How to do request correctly? Is in the right direction do I go?
Because as I said, I will need to do same thing with Revenue, Bounce Rate..
but I not fully understand how to combine Metrics and Dimensions without errors.
Thanks for any help

About my question:
As solution for my needs I used following combination in code:
To get all Channel groups ("Organic Search, Email, Direct, etc") I used following dimension:
ga:channelGrouping - it will return all
To get values for Sessions, Revenue, Transactions, Bounce Rate, etc I used following metrics:
ga:sessions
ga:transactionRevenue
ga:transactions
ga:bounceRate
Also here can be more metrics if it is needed.
Maybe it will be useful to somebody.
Actually, question about error with combination in question (with ga:acquisitionTrafficChannel) is still open :)

Related

How to get the metrics value in Google Business Profile Performance

I was using Google My business V4.9, I used to do
for (LocationMetrics locationMetrics : reportInsights.getLocationMetrics()) {
List <MetricValue> metricValue = locationMetrics.getMetricValues();
metricValue.get(0).getDimensionalValues().get(0).getValue())
and I was getting the value of the specific metric, but now after they have changed it to Business Profile Performance, I get a response of type GetDailyMetricsTimeSeriesResponse, I can't find any documentation that explains what is the structure of this response and how can I get the value of the metrics.
I'm using this answer to create the request
I can see that the new API have this object TimeSeries as a response.

specific IDs do not accept my access token in RestFB for Facebook

I try to fetch multiple objects through the RestFB API. I have a list of IDs (endpoints?) and want them to be bulk-fetched by RestFB. Therefore I use FacebookClient.fetchObjects(). The problem which now occurs is that one of the IDs in my list seems not to accept the token. I'm not that into the token system of facebook. The only token I generated is the app-token.
Two IDs used in the list:
working ID: 1104054513000418
not working ID: 1106761186063084
These IDs belong to posts which are from the same author and there is not real difference between them but the content.
Trying to fetch data by these IDs manually (no bulk-fetch) I have the same issue. So it is not an issue with the misusage of the multiple fetch method.
Code:
FacebookClient.AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken(appId, appSecurity);
FacebookClient fbClient = new DefaultFacebookClient(accessToken.getAccessToken());
// consider filteredSocialItems as given
List<String> filteredItemIDs = filteredSocialItems.stream()
.map({ item -> item.properties.get("sourceId") })
.collect(Collectors.toList());
JsonObject json = fbClient.fetchObjects(filteredItemIDs, JsonObject.class, Parameter.with("fields", "name,id"));
Exception:
Caught: com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#100) Requires user session (code 100, subcode null)
com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#100) Requires user session (code 100, subcode null)
at com.restfb.DefaultFacebookClient$DefaultGraphFacebookExceptionMapper.exceptionForTypeAndMessage(DefaultFacebookClient.java:1201)
at com.restfb.DefaultFacebookClient.throwFacebookResponseStatusExceptionIfNecessary(DefaultFacebookClient.java:1122)
at com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(DefaultFacebookClient.java:1063)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:974)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:936)
at com.restfb.DefaultFacebookClient.fetchObjects(DefaultFacebookClient.java:431)
at facebookImageRefresh.run(facebookImageRefresh.groovy:48)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:48)
Solving the problem was a bit exhausting. It was an issue with an old facebook app version.
Facebook apps are created within your Facebook developer account
Since Facebook changed a lof of its API rules here lies the problem. You cannot just access a post by its ID like using 1104054513000418 you also have to prefix the ID of the page/user who created that post. So if your page's ID is 589476469431696 you actually need to create a combined ID out of both like 589476469431696_1104054513000418 -> "{page_id}_{post_id}". I have no idea if this is interchangeable.
So after creating a new app I was able to get this to work.
Another info: as I was looking for a user access token all the time - I found it within my facebook app advanced settings. But it seems I don't need it any more.

Getting the subscription list under a topic in SNS via AWS SDK for Java

I have working on a project where I have to get the list of all the endpoint subscriptions that happened under the Application in AWS SNS Application.
ListEndpointsByPlatformApplicationRequest request = new ListEndpointsByPlatformApplicationRequest();
request.setPlatformApplicationArn(applicationArn);
ListEndpointsByPlatformApplicationResult result = sns.listEndpointsByPlatformApplication(request);
List<Endpoint> endpoints = result.getEndpoints();
for(Endpoint endpoint : result.getEndpoints()){
//System.out.println(endpoint.getEndpointArn());
count++;
}
The count always is 100 and the list that comes is also same I checked it via printing and getting the data out of it.
Where am I doing wrong. I know there is something connected with the token that we get using getNextToken() function but unable to do it.
Please help how to get the total number of endpoint subscription under an Application in SNS via AWS SDK using Java.
Thanks
Ankur :)
You need to use the returned token to return the next page of results as detailed
So your next request would be:
String token = tokenFromPreviousRequest();
ListEndpointsByPlatformApplicationRequest request =
new ListEndpointsByPlatformApplicationRequest();
request.setPlatformApplicationArn(applicationArn);
request.setNextToken(token);
ListEndpointsByPlatformApplicationResult result =
sns.listEndpointsByPlatformApplication(request);

Use Hbc Twitter Stream without specifying any track terms

I followed the Quickstart from HBC and I managed to get some tweets from the Twitter Stream specifying some track terms, here is the code:
/** Declare the host you want to connect to, the endpoint, and authentication (basic auth or oauth) */
Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
StreamingEndpoint endpoint = new StatusesFilterEndpoint();
// Optional: set up some followings and track terms
List<Long> followings = Lists.newArrayList(1234L, 566788L);
List<String> terms = Lists.newArrayList("twitter", "api");
endpoint.followings(followings);
endpoint.trackTerms(terms);
Is it possible to get the twitter Stream with Hbc without specifying any track terms?
I simply tried to remove the line "endpoint.trackTerms(terms);" but doing so it doesn't work.
Help me! Thanks!
It should work. I tried the example, and 'followed' myself and I received the Tweet I made whilst I was connected.
I suspect that the users you are following didn't have any activity whilst you were consuming the stream and that's why you didn't see any output - e.g. themselves Tweeting or somebody replying to one of their Tweets etc...
The follow parameter documentation outlines what activity you will see related to a followed user.
By the way, when specifying followings and trackTerms on the filter steam it's actually saying get me Tweets containing these terms or from these users. That's why you would see output when trackTerms was specified. This also goes for the additional locations parameter.

Duration in traffic google api

I am trying to find the travel duration from origin to destination using google's direction services api. I need to find out travel duration according to traffic conditions. I tried using javascript and it returns the duration in traffic value. But when i tried the same problem in java it doesn't seem to return the duration in traffic value. So how to obtain duration in traffic using direction services api of google?
URL url = new URL ("http://maps.googleapis.com/maps/api/directions/json?origin=" + URLEncoder.encode(origin, "UTF-8") +"&destination="+ URLEncoder.encode(destination, "UTF-8") +"&waypoints=optimize:true|Bagbazar,Kathmandu|Thapathali,Kathmandu|Kamal+Pokhari,Kathmandu"+"&sensor=false");
Above I have pasted the url I used to send to google server.
Below is the java script code, in the following code I can set durationInTraffic: true, which returns the time required to travel under traffic conditions. What is the equivalent process in java?
var request = {
origin:"Wollongong, Australia",
destination:"Sydney,Australia",
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true,
durationInTraffic: true
};
Take a look at the duration_in_traffic definition under the Legs section on the maps documentation page:
The directions request includes a departure_time parameter set to a value within a few minutes of the current time.
The request includes a valid Maps for Business client and signature parameter.
Traffic conditions are available for the requested route.
The directions request does not include stopover waypoints.
Maybe not all of the 4 conditions they list are being met?
There is also a JSON example on that page w/ a sample url you can use if it helps any.
In Google API URL add &departure_time=now it returns duration_in_traffic time .now means currentTime or you can put millisecond time in place of now.
if you adding waypoints then it will not returns duration_in_traffic
because google Api mentioned The directions request does not include stopover waypoints.
but if you adding waypoints using via:lat,long then it will returns duration in traffic because google API will not consider waypoints as stopover
If you set departure_time you can get duration_in_traffic for each your legs , but if you want duration_in_traffic for each steps you should use distance_matrix API , and merge this two .
In distance google API you need departure_time set .

Categories

Resources