16
16
17
17
package com .examples .cloud .speech ;
18
18
19
+ import com .google .auth .oauth2 .GoogleCredentials ;
19
20
import com .google .cloud .speech .v1beta1 .RecognitionAudio ;
20
21
import com .google .cloud .speech .v1beta1 .RecognitionConfig ;
21
22
import com .google .cloud .speech .v1beta1 .RecognitionConfig .AudioEncoding ;
25
26
import com .google .protobuf .TextFormat ;
26
27
27
28
import io .grpc .ManagedChannel ;
29
+ import io .grpc .ManagedChannelBuilder ;
28
30
import io .grpc .StatusRuntimeException ;
31
+ import io .grpc .auth .ClientAuthInterceptor ;
29
32
30
33
import org .apache .commons .cli .CommandLine ;
31
34
import org .apache .commons .cli .CommandLineParser ;
38
41
import java .net .URI ;
39
42
import java .util .Arrays ;
40
43
import java .util .List ;
44
+ import java .util .concurrent .Executors ;
41
45
import java .util .concurrent .TimeUnit ;
42
46
import java .util .logging .Level ;
43
47
import java .util .logging .Logger ;
@@ -49,15 +53,15 @@ public class SyncRecognizeClient {
49
53
50
54
private static final Logger logger = Logger .getLogger (SyncRecognizeClient .class .getName ());
51
55
52
- private static final List <String > OAUTH2_SCOPES =
53
- Arrays .asList ("https://www.googleapis.com/auth/cloud-platform" );
54
-
55
56
private final URI input ;
56
57
private final int samplingRate ;
57
58
58
59
private final ManagedChannel channel ;
59
60
private final SpeechGrpc .SpeechBlockingStub speechClient ;
60
61
62
+ private static final List <String > OAUTH2_SCOPES =
63
+ Arrays .asList ("https://www.googleapis.com/auth/cloud-platform" );
64
+
61
65
/**
62
66
* Construct client connecting to Cloud Speech server at {@code host:port}.
63
67
*/
@@ -78,6 +82,17 @@ public void shutdown() throws InterruptedException {
78
82
channel .shutdown ().awaitTermination (5 , TimeUnit .SECONDS );
79
83
}
80
84
85
+ static ManagedChannel createChannel (String host , int port ) throws IOException {
86
+ GoogleCredentials creds = GoogleCredentials .getApplicationDefault ();
87
+ creds = creds .createScoped (OAUTH2_SCOPES );
88
+ ManagedChannel channel =
89
+ ManagedChannelBuilder .forAddress (host , port )
90
+ .intercept (new ClientAuthInterceptor (creds , Executors .newSingleThreadExecutor ()))
91
+ .build ();
92
+
93
+ return channel ;
94
+ }
95
+
81
96
/** Send a non-streaming-recognize request to server. */
82
97
public void recognize () {
83
98
RecognitionAudio audio ;
@@ -179,7 +194,7 @@ public static void main(String[] args) throws Exception {
179
194
System .exit (1 );
180
195
}
181
196
182
- ManagedChannel channel = AsyncRecognizeClient . createChannel (host , port );
197
+ ManagedChannel channel = createChannel (host , port );
183
198
SyncRecognizeClient client = new SyncRecognizeClient (channel , URI .create (audioFile ), sampling );
184
199
try {
185
200
client .recognize ();
0 commit comments