Eveline van Hal Eveline van Hal - 1 month ago 7
Java Question

Google api: cast credentialBuilder to httprequestInitializer

I'm trying to access google analytics data, but keep getting a ClassCastException on my credentialBuilder. Here is my code:

(defn credential
[]
(doto (GoogleCredential$Builder.)
(.setTransport http-transport)
(.setJsonFactory json-factory)
(.setServiceAccountId "X")
(.setServiceAccountPrivateKeyFromP12File (File. "X"))
(.setServiceAccountScopes (AnalyticsReportingScopes/ANALYTICS_READONLY))
(.build)))

(defn analytics
[]
(doto (AnalyticsReporting$Builder. http-transport json-factory (credential))
(.setApplicationName "X")
(.build)))


The exact error I keep getting is :


com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder cannot be cast to com.google.api.client.http.HttpRequestInitializer


I try to follow Hello Analytics Reporting API V4: Java quickstart for service accounts example, what am I doing wrong?

Answer

doto returns the object passed as its first argument - in your case it will return instance of GoogleCredential$Builder and ignore the result of (.build) invocation. You need to change it to return the result of the call to (.build) instead:

(defn credential
  []
  (->
    (doto (GoogleCredential$Builder.)
      (.setTransport http-transport)
      (.setJsonFactory json-factory)
      (.setServiceAccountId "X")
      (.setServiceAccountPrivateKeyFromP12File (File. "X"))
      (.setServiceAccountScopes (AnalyticsReportingScopes/ANALYTICS_READONLY)))
    (.build))

doto is macro-expanded to a form like the following:

(doto (StringBuilder.)
  (.append "a")
  (.append "b"))

becomes

(let [obj (StringBuilder.)]
  (.append obj "a")
  (.append obj "b")
  obj)
Comments