3434import com .google .cloud .speech .v1beta1 .AsyncRecognizeResponse ;
3535import com .google .protobuf .TextFormat ;
3636
37- import google .longrunning .Operation ;
37+ import com .google .longrunning .GetOperationRequest ;
38+ import com .google .longrunning .Operation ;
39+ import com .google .longrunning .OperationsGrpc ;
3840
3941import io .grpc .ManagedChannel ;
4042import io .grpc .StatusRuntimeException ;
@@ -76,6 +78,7 @@ public class AsyncRecognizeClient {
7678
7779 private final ManagedChannel channel ;
7880 private final SpeechGrpc .SpeechBlockingStub stub ;
81+ private final OperationsGrpc .OperationsBlockingStub op ;
7982
8083 /**
8184 * Construct client connecting to Cloud Speech server at {@code host:port}.
@@ -94,6 +97,8 @@ public AsyncRecognizeClient(String host, int port, URI input, int samplingRate)
9497 .intercept (new ClientAuthInterceptor (creds , Executors .newSingleThreadExecutor ()))
9598 .build ();
9699 stub = SpeechGrpc .newBlockingStub (channel );
100+ op = OperationsGrpc .newBlockingStub (channel );
101+
97102 logger .info ("Created stub for " + host + ":" + port );
98103 }
99104
@@ -124,23 +129,38 @@ public void recognize() {
124129 .setAudio (audio )
125130 .build ();
126131
127- Operation operation ;
132+ Operation operation , status ;
128133 try {
129134 operation = stub .asyncRecognize (request );
130135
131136 //Print the long running operation handle
132- System .out .println (operation );
137+ logger .log (Level .INFO , String .format ("Operation handle: %s, URI: %s" , operation .getName (),
138+ input .toString ()));
133139 } catch (StatusRuntimeException e ) {
134140 logger .log (Level .WARNING , "RPC failed: {0}" , e .getStatus ());
135141 return ;
136142 }
137143
138- while (operation .hasDone ()) {
139- System .out .println (operation );
140- //Sleep for 1 s
141- Thread .sleep (1000 );
144+ while (true ) {
145+ try {
146+ logger .log (Level .INFO , "Waiting 2s for operation, {0} processing..." , operation .getName ());
147+ Thread .sleep (2000 );
148+ GetOperationRequest operationReq = GetOperationRequest .newBuilder ()
149+ .setName (operation .getName ())
150+ .build ();
151+ status = op .getOperation (
152+ GetOperationRequest .newBuilder ()
153+ .setName (operation .getName ())
154+ .build ()
155+ );
156+
157+ if (status .getDone ()) break ;
158+ }catch (Exception ex ) {
159+ logger .log (Level .WARNING , ex .getMessage ());
160+ }
142161 }
143- //logger.info("Received response: " + TextFormat.printToString(response));
162+
163+ logger .info ("Received response: " + status .getResponse ());
144164 }
145165
146166 public static void main (String [] args ) throws Exception {
0 commit comments