GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — added okhttp3-ws to the pom.xml and updated javadoc and imports · einsnull/java-sdk@37bc0e8

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pom.xml
  • src
    • main/java/com/ibm/watson/developer_cloud/speech_to_text/v1
      • SpeechToText.java
      • websocket
        • ResponseListener.java
        • WebSocketManager.java
    • test/java/com/ibm/watson/developer_cloud/speech_to_text/v1
      • SpeechToTextIT.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pom.xml‎

Copy file name to clipboardExpand all lines: pom.xml
+7-1Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
34
<modelVersion>4.0.0</modelVersion>
45
<groupId>com.ibm.watson.developer_cloud</groupId>
56
<version>2.10.1-SNAPSHOT</version>
@@ -22,6 +23,11 @@
2223
<artifactId>okhttp</artifactId>
2324
<version>3.2.0</version>
2425
</dependency>
26+
<dependency>
27+
<groupId>com.squareup.okhttp3</groupId>
28+
<artifactId>okhttp-ws</artifactId>
29+
<version>3.2.0</version>
30+
</dependency>
2531
<dependency>
2632
<groupId>com.squareup.okhttp3</groupId>
2733
<artifactId>okhttp-urlconnection</artifactId>
Collapse file

‎src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToText.java‎

Copy file name to clipboardExpand all lines: src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToText.java
+16Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,14 @@
2929
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechSession;
3030
import com.ibm.watson.developer_cloud.speech_to_text.v1.util.MediaTypeUtils;
3131
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.RecognizeDelegate;
32+
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.ResponseListener;
33+
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.WebSocketManager;
3234
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.WebSocketSpeechToTextClient;
3335
import com.ibm.watson.developer_cloud.util.GsonSingleton;
3436
import com.ibm.watson.developer_cloud.util.ResponseConverterUtils;
3537
import com.ibm.watson.developer_cloud.util.Validator;
3638

39+
import okhttp3.OkHttpClient;
3740
import okhttp3.Request;
3841

3942
/**
@@ -314,4 +317,17 @@ public void recognizeUsingWebSockets(InputStream audio, RecognizeOptions options
314317
WebSocketSpeechToTextClient webSocket = new WebSocketSpeechToTextClient(url + PATH_RECOGNIZE, getToken());
315318
webSocket.recognize(audio, options, delegate);
316319
}
320+
321+
public void recognizeUsingOkhttpWebsocket(InputStream audio, RecognizeOptions options) {
322+
String url = getEndPoint().replaceFirst("(https|http)", "wss");
323+
WebSocketManager wsManager = new WebSocketManager(url + PATH_RECOGNIZE, new OkHttpClient.Builder().build(),getToken(), new ResponseListener() {
324+
@Override
325+
public void onResponse(String response) {
326+
System.out.println(response);
327+
}
328+
});
329+
//wsManager.recognize(audio, options);
330+
wsManager.connect(options);
331+
332+
}
317333
}
Collapse file

‎src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/websocket/ResponseListener.java‎

Copy file name to clipboard
+35Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Copyright 2015 IBM Corp. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
package com.ibm.watson.developer_cloud.speech_to_text.v1.websocket;
15+
16+
/**
17+
* The listener interface for receiving response events.
18+
* The class that is interested in processing a response
19+
* event implements this interface, and the object created
20+
* with that class is registered with a component using the
21+
* component's <code>addResponseListener<code> method. When
22+
* the response event occurs, that object's appropriate
23+
* method is invoked.
24+
*
25+
* @see ResponseEvent
26+
*/
27+
public interface ResponseListener {
28+
29+
/**
30+
* On response.
31+
*
32+
* @param response the response
33+
*/
34+
void onResponse(String response);
35+
}
Collapse file

‎src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/websocket/WebSocketManager.java‎

Copy file name to clipboard
+213Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
/**
2+
* Copyright 2015 IBM Corp. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
package com.ibm.watson.developer_cloud.speech_to_text.v1.websocket;
15+
16+
import java.io.IOException;
17+
import java.io.InputStream;
18+
import java.util.Arrays;
19+
20+
import com.google.gson.Gson;
21+
import com.google.gson.JsonObject;
22+
import com.google.gson.JsonParser;
23+
import com.ibm.watson.developer_cloud.http.HttpHeaders;
24+
import com.ibm.watson.developer_cloud.speech_to_text.v1.RecognizeOptions;
25+
26+
import okhttp3.OkHttpClient;
27+
import okhttp3.Request;
28+
import okhttp3.RequestBody;
29+
import okhttp3.Response;
30+
import okhttp3.ResponseBody;
31+
import okhttp3.ws.WebSocket;
32+
import okhttp3.ws.WebSocketCall;
33+
import okhttp3.ws.WebSocketListener;
34+
import okio.Buffer;
35+
36+
/**
37+
* WebSocket manager
38+
*/
39+
public class WebSocketManager implements WebSocketListener {
40+
41+
private static final String MODEL = "model";
42+
private static final String START = "start";
43+
private static final String STOP = "stop";
44+
private static final String ACTION = "action";
45+
46+
private String url;
47+
private OkHttpClient client;
48+
private ResponseListener listener;
49+
50+
private volatile boolean connecting;
51+
private volatile boolean connected;
52+
53+
private static final int FOUR_KB = 4096;
54+
55+
/** The socket. */
56+
public WebSocket socket;
57+
58+
private String token;
59+
60+
/**
61+
* Instantiates a new web socket manager.
62+
*
63+
* @param url the url
64+
* @param client the client
65+
* @param token the token
66+
* @param listener the listener
67+
*/
68+
public WebSocketManager(String url, OkHttpClient client, String token, ResponseListener listener) {
69+
this.url = url;
70+
this.client = client;
71+
this.token = token;
72+
this.listener = listener;
73+
}
74+
75+
/**
76+
* Connect.
77+
*
78+
* @param options the options
79+
*/
80+
public void connect(RecognizeOptions options) {
81+
if(connecting != true) {
82+
connecting = true;
83+
84+
String speechModel = options.getModel() != null ? "?model=" + options.getModel() : "";
85+
Request connectionRequest = new Request.Builder()
86+
.url(url + speechModel)
87+
.addHeader(HttpHeaders.X_WATSON_AUTHORIZATION_TOKEN, token)
88+
.build();
89+
WebSocketCall.create(client, connectionRequest).enqueue(this);
90+
}
91+
}
92+
93+
/**
94+
* Force close.
95+
*
96+
* @throws IOException Signals that an I/O exception has occurred.
97+
*/
98+
public void forceClose() throws IOException {
99+
socket.close(1000, "User forced socket close");
100+
}
101+
102+
/**
103+
* Send input steam.
104+
*
105+
* @param inputStream the input stream
106+
*/
107+
public void sendInputSteam(InputStream inputStream) {
108+
if (!connected || socket == null)
109+
throw new IllegalStateException("WebSocket not connected; call connect()");
110+
111+
try {
112+
byte[] buffer = new byte[FOUR_KB];
113+
int read;
114+
while ((read = inputStream.read(buffer)) > 0) {
115+
if (read == FOUR_KB)
116+
socket.sendMessage(RequestBody.create(WebSocket.BINARY, buffer));
117+
else
118+
socket.sendMessage(RequestBody.create(WebSocket.BINARY, Arrays.copyOfRange(buffer, 0, read)));
119+
120+
Thread.sleep(20);
121+
}
122+
inputStream.close();
123+
} catch (Exception e) {
124+
throw new RuntimeException(e);
125+
}
126+
}
127+
128+
/**
129+
* Recognize.
130+
*
131+
* @param stream the stream
132+
* @param options the options
133+
*/
134+
public void recognize(InputStream stream, RecognizeOptions options) {
135+
if (connected != true)
136+
connect(options);
137+
138+
try {
139+
socket.sendMessage(RequestBody.create(WebSocket.TEXT, buildStartMessage(options).body().toString()));
140+
sendInputSteam(stream);
141+
socket.sendMessage(RequestBody.create(WebSocket.TEXT, buildStopMessage().body().toString()));
142+
} catch (IOException e) {
143+
e.printStackTrace();
144+
}
145+
146+
147+
}
148+
149+
/**
150+
* Builds the start message.
151+
*
152+
* @param options the options
153+
* @return the request
154+
*/
155+
public Request buildStartMessage(RecognizeOptions options) {
156+
JsonObject startMessage = new JsonParser().parse(new Gson().toJson(options)).getAsJsonObject();
157+
startMessage.remove(MODEL);
158+
startMessage.addProperty(ACTION, START);
159+
return new Request.Builder().post(RequestBody.create(WebSocket.TEXT, startMessage.toString())).build();
160+
}
161+
162+
private Request buildStopMessage() {
163+
JsonObject stopMessage = new JsonObject();
164+
stopMessage.addProperty(ACTION, STOP);
165+
return new Request.Builder().post(RequestBody.create(WebSocket.TEXT, stopMessage.toString())).build();
166+
}
167+
168+
/* (non-Javadoc)
169+
* @see okhttp3.ws.WebSocketListener#onOpen(okhttp3.ws.WebSocket, okhttp3.Response)
170+
*/
171+
@Override
172+
public void onOpen(WebSocket webSocket, Response response) {
173+
socket = webSocket;
174+
connecting = false;
175+
connected = true;
176+
}
177+
178+
/* (non-Javadoc)
179+
* @see okhttp3.ws.WebSocketListener#onFailure(java.io.IOException, okhttp3.Response)
180+
*/
181+
@Override
182+
public void onFailure(IOException e, Response response) {
183+
connecting = false;
184+
connected = false;
185+
186+
}
187+
188+
/* (non-Javadoc)
189+
* @see okhttp3.ws.WebSocketListener#onMessage(okhttp3.ResponseBody)
190+
*/
191+
@Override
192+
public void onMessage(ResponseBody responseBody) throws IOException {
193+
listener.onResponse(responseBody.string());
194+
}
195+
196+
/* (non-Javadoc)
197+
* @see okhttp3.ws.WebSocketListener#onPong(okio.Buffer)
198+
*/
199+
@Override
200+
public void onPong(Buffer buffer) {
201+
202+
}
203+
204+
/* (non-Javadoc)
205+
* @see okhttp3.ws.WebSocketListener#onClose(int, java.lang.String)
206+
*/
207+
@Override
208+
public void onClose(int i, String s) {
209+
connecting = false;
210+
connected = false;
211+
}
212+
213+
}
Collapse file

‎src/test/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToTextIT.java‎

Copy file name to clipboardExpand all lines: src/test/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToTextIT.java
+15Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,4 +214,19 @@ public void onMessage(SpeechResults speechResults) {
214214
assertNotNull(asyncResults);
215215
}
216216

217+
@Test
218+
public void testRecognizeOkhttpWebSocket() throws FileNotFoundException, InterruptedException {
219+
RecognizeOptions options = new RecognizeOptions();
220+
options.continuous(true).interimResults(true);
221+
options.inactivityTimeout(40).timestamps(true).maxAlternatives(2);
222+
options.model(EN_BROADBAND16K).contentType(HttpMediaType.AUDIO_WAV);
223+
224+
service.recognizeUsingOkhttpWebsocket(new FileInputStream(
225+
"src/test/resources/speech_to_text/sample1.wav"), options);
226+
227+
lock.await(20000, TimeUnit.MILLISECONDS);
228+
//assertNotNull(asyncResults);
229+
}
230+
231+
217232
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.