Browse Source

Update Natural Language example to use Google Application Default Credentials
as implemented by google/auth-library-swift.

Tim Burks 8 years ago
parent
commit
82c0ca8325

+ 1 - 1
Examples/NaturalLanguage/PackageManager/Package.swift

@@ -19,6 +19,6 @@ let package = Package (
     dependencies: [
         .Package(url: "https://github.com/grpc/grpc-swift.git", Version(0,2,4)),
         .Package(url: "https://github.com/apple/swift-protobuf.git", Version(1,0,2)),
-        .Package(url: "https://github.com/google/auth-library-swift.git", Version(0,3,2)),
+        .Package(url: "https://github.com/google/auth-library-swift.git", Version(0,3,3)),
     ]
 )

+ 5 - 4
Examples/NaturalLanguage/PackageManager/README.md

@@ -16,9 +16,10 @@ Calls require a Google project ID and service account credentials.
 To create a project ID, visit the 
 [Google Cloud Console](https://cloud.google.com/console).
 
-After enabling the Cloud Natural Language API for your project,
-create and download service account credentials, saving them
-in ~/.credentials/credentials.json.
-
 Service account support is provided by Google's 
 [Auth Library for Swift](https://github.com/google/auth-library-swift).
+After enabling the Cloud Natural Language API for your project,
+create and download service account credentials. Then set the
+GOOGLE_APPLICATION_CREDENTIALS environment variable to point to 
+the file containing these credentials.
+

+ 41 - 48
Examples/NaturalLanguage/PackageManager/Sources/main.swift

@@ -17,66 +17,59 @@ import Foundation
 import gRPC
 import OAuth2
 
-let CREDENTIALS = ".credentials/credentials.json"
+if let provider = DefaultTokenProvider() {
+  let sem = DispatchSemaphore(value: 0)
+  try provider.withToken() {(token, error) -> Void in
+    if let token = token {
 
-if #available(OSX 10.12, *) {
-  let homeURL = FileManager.default.homeDirectoryForCurrentUser
-  let credentialsURL = homeURL.appendingPathComponent(CREDENTIALS)
-  if let provider = ServiceAccountTokenProvider(credentialsURL:credentialsURL) {
-    let sem = DispatchSemaphore(value: 0)
-    try provider.withToken() {(token, error) -> Void in
-      if let token = token {
+      gRPC.initialize()
 
-        gRPC.initialize()
-
-        guard let authToken = token.AccessToken else {
-          print("ERROR: No OAuth token is available.")
-          exit(-1)
-        }
-
-        let certificateURL = URL(fileURLWithPath:"roots.pem")
-        let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
-        let service = Google_Cloud_Language_V1_LanguageServiceService(address:"language.googleapis.com",
-                                                                      certificates:certificates,
-                                                                      host:nil)
+      guard let authToken = token.AccessToken else {
+        print("ERROR: No OAuth token is available.")
+        exit(-1)
+      }
 
-        service.metadata = Metadata(["authorization":"Bearer " + authToken])
+      let certificateURL = URL(fileURLWithPath:"roots.pem")
+      let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
+      let service = Google_Cloud_Language_V1_LanguageServiceService(address:"language.googleapis.com",
+                                                                    certificates:certificates,
+                                                                    host:nil)
 
-        var request = Google_Cloud_Language_V1_AnnotateTextRequest()
+      service.metadata = Metadata(["authorization":"Bearer " + authToken])
 
-        var document = Google_Cloud_Language_V1_Document()
-        document.type = .plainText
-        document.content = "The Caterpillar and Alice looked at each other for some time in silence: at last the Caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice. `Who are you?' said the Caterpillar."
-        request.document = document
+      var request = Google_Cloud_Language_V1_AnnotateTextRequest()
 
-        var features = Google_Cloud_Language_V1_AnnotateTextRequest.Features()
-        features.extractSyntax = true
-        features.extractEntities = true
-        features.extractDocumentSentiment = true
-        features.extractEntitySentiment = true
-        features.classifyText = true
-        request.features = features
+      var document = Google_Cloud_Language_V1_Document()
+      document.type = .plainText
+      document.content = "The Caterpillar and Alice looked at each other for some time in silence: at last the Caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice. `Who are you?' said the Caterpillar."
+      request.document = document
 
-        print("\(request)")
+      var features = Google_Cloud_Language_V1_AnnotateTextRequest.Features()
+      features.extractSyntax = true
+      features.extractEntities = true
+      features.extractDocumentSentiment = true
+      features.extractEntitySentiment = true
+      features.classifyText = true
+      request.features = features
 
-        do {
-          let result = try service.annotatetext(request)
-          print("\(result)")
-        } catch (let error) {
-          print("ERROR: \(error)")
-        }
+      print("\(request)")
 
+      do {
+        let result = try service.annotatetext(request)
+        print("\(result)")
+      } catch (let error) {
+        print("ERROR: \(error)")
       }
-      if let error = error {
-        print("ERROR \(error)")
-      }
-      sem.signal()
+
+    }
+    if let error = error {
+      print("ERROR \(error)")
     }
-    _ = sem.wait(timeout: DispatchTime.distantFuture)
-  } else {
-    print("Unable to read service account credentials from $HOME/\(CREDENTIALS).")
+    sem.signal()
   }
+  _ = sem.wait(timeout: DispatchTime.distantFuture)
 } else {
-  print("This sample requires OSX 10.12 or later.")
+  print("Unable to create default token provider.")
 }
 
+