2

I am trying to hit google analytics through GAE APIs from a cross platform Java desktop application. I followed sample code from github but due to threading problem the request isn't being executed.

https://github.com/GoogleCloudPlatform/appengine-googleanalytics-java/blob/master/src/main/java/com/google/appengine/analytics/tracking/GoogleAnalyticsTracking.java

Here is my sample code:

ThreadManager.currentRequestThreadFactory().newThread(new Runnable() {
    @Override
    public void run() {
        try {
            GoogleAccountTracker.trackEventToGoogleAnalytics("category1", "action1", "label1", "value1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});
public static int trackEventToGoogleAnalytics(String category, String action, String label, String value) throws IOException {
    Application.LOGGER.info("trackEventToGoogleAnalytics() started");

    Map<String, String> map = new LinkedHashMap<>();
    map.put("v", "1");             // Version.
    map.put("tid", gaTrackingId);
    map.put("cid", gaClientId);
    map.put("t", "event");         // Event hit type.
    map.put("ec", encode(category, true));
    map.put("ea", encode(action, true));
    map.put("el", encode(label, false));
    map.put("ev", encode(value, false));

    HTTPRequest request = new HTTPRequest(GA_URL_ENDPOINT, HTTPMethod.POST);
    request.addHeader(CONTENT_TYPE_HEADER);
    request.setPayload(getPostData(map));

    HTTPResponse response = urlFetchService.fetch(request);

    byte[] content = response.getContent();
    URL finalUrl = response.getFinalUrl();

    // 200, 404, 500, etc
    int responseCode = response.getResponseCode();
    List<HTTPHeader> headers = response.getHeaders();

    for(HTTPHeader header : headers) {
        String headerName = header.getName();
        String headerValue = header.getValue();
        Application.LOGGER.info(headerName + " " + headerValue);
    }

    Application.LOGGER.info("trackEventToGoogleAnalytics() ended");

    return 0; //httpResponse.getResponseCode();
}

The exception I am getting:

Caused by: java.lang.NullPointerException: Current thread is not associated with any request and is not a background thread
    at com.google.appengine.api.ThreadManager.getCurrentEnvironmentOrThrow(ThreadManager.java:106)
    at com.google.appengine.api.ThreadManager.currentRequestThreadFactory(ThreadManager.java:47)
iamcrypticcoder
  • 2,609
  • 4
  • 27
  • 50
  • 1
    I didn't find any suitable SO thread that satisfy my problem. If you can find please provide me instead of marking as duplicate question. I will remove mine if I get the working solution. – iamcrypticcoder Oct 16 '19 at 09:53

0 Answers0