Skip to content

Commit c61e9ab

Browse files
committed
Half-done work for posting audio files
1 parent e227c02 commit c61e9ab

File tree

9 files changed

+205
-44
lines changed

9 files changed

+205
-44
lines changed

samples/audio/TOTC.m4a

162 KB
Binary file not shown.

src/main/java/com/speechscrubber/Constants.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
public class Constants {
44

55
public static final String BASE_URL = "https://api.rev.ai/revspeech/v1beta";
6+
public static final String JOBS_URL = BASE_URL + "/jobs/";
7+
68
public static final String API_KEY_SYSTEM_PROP = "REV_API_KEY";
79

810
}

src/main/java/com/speechscrubber/RevSpeechService.java

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,18 @@
33
import java.util.List;
44

55
import javax.json.JsonObject;
6-
import javax.print.attribute.standard.Media;
6+
import javax.servlet.http.HttpServletRequest;
77
import javax.ws.rs.GET;
88
import javax.ws.rs.POST;
99
import javax.ws.rs.Path;
10+
import javax.ws.rs.PathParam;
1011
import javax.ws.rs.Produces;
1112
import javax.ws.rs.QueryParam;
12-
import javax.ws.rs.PathParam;
13+
import javax.ws.rs.core.Context;
1314
import javax.ws.rs.core.MediaType;
1415

1516
import com.speechscrubber.job.JobChecker;
17+
import com.speechscrubber.job.JobPoster;
1618
import com.speechscrubber.parser.TimeStampJSONParser;
1719

1820
@Path("/speech")
@@ -38,7 +40,7 @@ public String isTranscriptReady(@PathParam("id") String id) {
3840
@Path("/{id}/transcript")
3941
@Produces(MediaType.APPLICATION_JSON)
4042
public JsonObject getTranscript(@PathParam("id") String id) throws Exception {
41-
return jc.getTranscript(id);
43+
return jc.getTranscript(id);
4244
}
4345

4446
@GET
@@ -64,4 +66,14 @@ private void setSearchPhrase(String phrase) {
6466
private String getSearchPhrase() {
6567
return this.searchPhrase;
6668
}
69+
70+
@POST
71+
@Path("/upload")
72+
@Produces(MediaType.APPLICATION_JSON)
73+
public String postAudio(@Context HttpServletRequest request) {
74+
System.out.println("Posting audio...");
75+
JobPoster jobPoster = new JobPoster();
76+
return jobPoster.postAudio(request);
77+
}
78+
6779
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.speechscrubber;
2+
3+
public class Utils {
4+
5+
public static String getApiKey() {
6+
return System.getenv(Constants.API_KEY_SYSTEM_PROP);
7+
}
8+
9+
}

src/main/java/com/speechscrubber/job/JobChecker.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import javax.json.JsonValue.ValueType;
1212

1313
import com.speechscrubber.Constants;
14+
import com.speechscrubber.Utils;
1415
import com.speechscrubber.web.HttpUtils;
1516

1617
public class JobChecker {
@@ -22,10 +23,6 @@ public class JobChecker {
2223

2324
private HttpUtils httpUtils = new HttpUtils();
2425

25-
public String getApiKey() {
26-
return System.getenv(Constants.API_KEY_SYSTEM_PROP);
27-
}
28-
2926
public boolean isTranscriptReady(String jobId) {
3027
try {
3128
verifyJobIdFormat(jobId);
@@ -64,7 +61,7 @@ public JsonObject getTranscript(String jobId) throws JobException {
6461

6562
Map<String, String> createRequestHeaders() {
6663
Map<String, String> requestProperties = new HashMap<String, String>();
67-
requestProperties.put("Authorization", "Bearer " + getApiKey());
64+
requestProperties.put("Authorization", "Bearer " + Utils.getApiKey());
6865
return requestProperties;
6966
}
7067

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.speechscrubber.job;
2+
3+
import java.io.OutputStream;
4+
import java.io.OutputStreamWriter;
5+
import java.io.PrintWriter;
6+
import java.net.HttpURLConnection;
7+
import java.util.Map;
8+
import java.util.Map.Entry;
9+
10+
import javax.servlet.http.HttpServletRequest;
11+
12+
import com.speechscrubber.Constants;
13+
import com.speechscrubber.web.HttpUtils;
14+
15+
public class JobPoster {
16+
17+
private HttpUtils httpUtils = new HttpUtils();
18+
19+
public String postAudio(HttpServletRequest request) {
20+
System.out.println("(JobPoster) Posting audio...");
21+
StringBuilder builder = new StringBuilder();
22+
try {
23+
System.out.println("Getting auth header...");
24+
Map<String, String> requestHeaders = httpUtils.getAuthorizationHeader();
25+
System.out.println("Creating connection...");
26+
HttpURLConnection connection = httpUtils.createHttpUrlConnection(Constants.JOBS_URL, requestHeaders, "POST");
27+
// connection.setRequestProperty("Content-Type", "multipart/form-data");
28+
connection.setRequestProperty("Content-Type", "application/json");
29+
30+
String fileName = request.getParameter("filename");
31+
System.out.println("Got file name: " + fileName + "...");
32+
33+
System.out.println("Getting output stream...");
34+
OutputStream output = connection.getOutputStream();
35+
36+
System.out.println("Setting up writer...");
37+
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
38+
39+
Map<String, String> env = System.getenv();
40+
for (Entry<String, String> entry : env.entrySet()) {
41+
System.out.println("(Env) " + entry.getKey() + "=[" + entry.getValue() + "]");
42+
}
43+
44+
writer.append("\r\n");
45+
46+
String body = "{\"media_url\": \"https://support.rev.com/hc/en-us/article_attachments/200043975/FTC_Sample_1_-_Single.mp3\",\"metadata\": \"AYOHO test\""/*
47+
* ,\"callback_url\": \"
48+
* https
49+
* :
50+
* /
51+
* /
52+
* www
53+
* .
54+
* example
55+
* .
56+
* com
57+
* /
58+
* callback\
59+
*/ + "}";
60+
writer.append(body).append("\r\n");
61+
62+
// String paramMedia = "media=@" + env.get("PWD") + "/" + fileName + ";type=audio/*";
63+
// // String paramMedia = "media=@https://support.rev.com/hc/en-us/article_attachments/200043975/FTC_Sample_1_-_Single.mp3;type=audio/*";
64+
// System.out.println("Writing: [" + paramMedia + "]");
65+
// writer.append(paramMedia).append("\r\n");
66+
// // output.write((paramMedia + "\r\n").getBytes("UTF-8"));
67+
//
68+
// String paramOptions = "options={\"metadata\":\"AYOHO test\"}";
69+
// System.out.println("Writing: [" + paramOptions + "]");
70+
// writer.append(paramOptions).append("\r\n");
71+
// // output.write((paramOptions + "\r\n").getBytes("UTF-8"));
72+
73+
writer.flush();
74+
75+
// output.write(("media=@" + env.get("PWD") + "/TOTC.m4a;type=audio/*").getBytes("UTF-8"));
76+
// output.write(("options={\"metadata\":\"AYOHO test\"}").getBytes("UTF-8"));
77+
78+
// System.out.println("Getting input stream...");
79+
// InputStream inStream = request.getInputStream();
80+
// byte[] buffer = new byte[1024];
81+
// int totalBytes = 0;
82+
// int bytesRead = 0;
83+
// System.out.println("Starting loop...");
84+
// while ((bytesRead = inStream.read(buffer)) > -1) {
85+
// output.write(buffer);
86+
// System.out.println("\tRead [" + bytesRead + "] bytes");
87+
// totalBytes += bytesRead;
88+
// }
89+
// System.out.println("Posting total bytes: " + totalBytes);
90+
// connection.setFixedLengthStreamingMode(totalBytes);
91+
92+
System.out.println("Reading connection response...");
93+
builder.append(httpUtils.readConnectionResponse(connection));
94+
} catch (Exception e) {
95+
e.printStackTrace();
96+
System.out.println("Caught exception: " + e);
97+
builder.append("Failed to post audio: " + e);
98+
}
99+
100+
return builder.toString();
101+
}
102+
103+
private void test() {
104+
105+
}
106+
}

src/main/java/com/speechscrubber/web/HttpUtils.java

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,25 @@
44
import java.io.IOException;
55
import java.io.InputStream;
66
import java.io.InputStreamReader;
7+
import java.io.OutputStream;
78
import java.net.HttpURLConnection;
89
import java.net.MalformedURLException;
910
import java.net.ProtocolException;
1011
import java.net.URL;
12+
import java.util.HashMap;
1113
import java.util.Map;
1214
import java.util.Map.Entry;
1315

16+
import com.speechscrubber.Utils;
17+
1418
public class HttpUtils {
1519

20+
public Map<String, String> getAuthorizationHeader() {
21+
Map<String, String> requestProperties = new HashMap<String, String>();
22+
requestProperties.put("Authorization", "Bearer " + Utils.getApiKey());
23+
return requestProperties;
24+
}
25+
1626
public String sendGetRequest(String targetUrl) {
1727
return sendGetRequest(targetUrl, null);
1828
}
@@ -51,30 +61,66 @@ public String sendPostRequest(String targetUrl) {
5161
return sendPostRequest(targetUrl, null);
5262
}
5363

54-
HttpURLConnection createHttpUrlConnection(String targetUrl, Map<String, String> requestProperties, String requestType) throws MalformedURLException, IOException, ProtocolException {
64+
public String sendPostRequest(String targetUrl, Map<String, String> requestProperties, Object body) {
65+
HttpURLConnection connection = null;
66+
try {
67+
connection = createHttpUrlConnection(targetUrl, requestProperties, "POST");
68+
connection.setDoOutput(true);
69+
// TODO - ayoho
70+
// See https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests/2793153#2793153
71+
// connection.setFixedLengthStreamingMode(contentLength);
72+
connection.setRequestProperty("Content-Type", "audio/mpeg");
73+
74+
try (OutputStream output = connection.getOutputStream()) {
75+
// output.write(query.getBytes(charset));
76+
}
77+
78+
return readConnectionResponse(connection);
79+
} catch (Exception e) {
80+
e.printStackTrace();
81+
} finally {
82+
if (connection != null) {
83+
connection.disconnect();
84+
}
85+
}
86+
return null;
87+
}
88+
89+
public HttpURLConnection createHttpUrlConnection(String targetUrl, Map<String, String> requestProperties, String requestType) throws MalformedURLException, IOException, ProtocolException {
5590
URL url = new URL(targetUrl);
5691
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
5792
connection.setRequestMethod(requestType);
5893
connection.setUseCaches(false);
59-
connection.setDoOutput(false);
94+
if (requestType != null && "post".equalsIgnoreCase(requestType)) {
95+
connection.setDoOutput(true);
96+
}
6097
if (requestProperties != null) {
6198
for (Entry<String, String> entry : requestProperties.entrySet()) {
6299
connection.setRequestProperty(entry.getKey(), entry.getValue());
63100
}
64101
}
65-
// connection.setRequestProperty("Authorization", "Bearer " + getApiKey());
66102
return connection;
67103
}
68104

69-
String readConnectionResponse(HttpURLConnection connection) throws IOException {
70-
InputStream is = connection.getInputStream();
105+
public String readConnectionResponse(HttpURLConnection connection) throws IOException {
106+
int responseStatus = connection.getResponseCode();
107+
InputStream is;
108+
if (responseStatus > 299) {
109+
System.out.println("Got an error status (" + responseStatus + ")");
110+
is = connection.getErrorStream();
111+
} else {
112+
System.out.println("Got a successful status (" + responseStatus + ")");
113+
is = connection.getInputStream();
114+
}
115+
71116
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
72117
StringBuilder response = new StringBuilder();
73118
String line;
74119
while ((line = reader.readLine()) != null) {
75120
response.append(line);
76121
}
77122
reader.close();
123+
System.out.println("Response: " + response.toString());
78124
return response.toString();
79125
}
80126

src/main/webapp/js/main.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,12 @@ $(document).ready(function() {
2727
jobID = response.id;
2828
deferred.resolve(response.id);
2929
} else {
30+
console.log("I reject you, Satan!");
3031
deferred.reject();
3132
}
3233
},
3334
error: function(jqXHR){
35+
console.log("Oh noes!");
3436
deferred.reject(jqXHR);
3537
}
3638
});

test/com/speechscrubber/job/JobCheckerTest.java

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,56 +3,43 @@
33
import static org.junit.Assert.assertEquals;
44
import static org.junit.Assert.assertFalse;
55
import static org.junit.Assert.assertNotNull;
6-
import static org.junit.Assert.assertNull;
76
import static org.junit.Assert.assertTrue;
87
import static org.junit.Assert.fail;
98

109
import javax.json.Json;
1110
import javax.json.JsonObject;
1211
import javax.json.JsonObjectBuilder;
1312

14-
import org.junit.After;
1513
import org.junit.Before;
1614
import org.junit.Test;
1715

18-
import com.speechscrubber.Constants;
19-
2016
public class JobCheckerTest {
2117

2218
JobChecker checker;
23-
String apiSysPropValue = null;
2419

2520
@Before
2621
public void beforeTest() {
2722
checker = new JobChecker();
28-
apiSysPropValue = System.getProperty(Constants.API_KEY_SYSTEM_PROP);
29-
}
30-
31-
@After
32-
public void afterTest() {
33-
if (apiSysPropValue != null) {
34-
System.setProperty(Constants.API_KEY_SYSTEM_PROP, apiSysPropValue);
35-
}
36-
}
37-
38-
/******************************************************* getApiKey *******************************************************/
39-
40-
@Test
41-
public void test_getApiKey_keyNotSet() {
42-
System.clearProperty(Constants.API_KEY_SYSTEM_PROP);
43-
44-
String key = checker.getApiKey();
45-
assertNull("API key was not null but should have been. Key was [" + key + "].", key);
4623
}
4724

48-
@Test
49-
public void test_getApiKey_keySet() {
50-
String actualKey = "test";
51-
System.setProperty(Constants.API_KEY_SYSTEM_PROP, actualKey);
52-
53-
String foundKey = checker.getApiKey();
54-
assertEquals("API key did not match expected value.", actualKey, foundKey);
55-
}
25+
// /******************************************************* getApiKey *******************************************************/
26+
//
27+
// @Test
28+
// public void test_getApiKey_keyNotSet() {
29+
// System.clearProperty(Constants.API_KEY_SYSTEM_PROP);
30+
//
31+
// String key = checker.getApiKey();
32+
// assertNull("API key was not null but should have been. Key was [" + key + "].", key);
33+
// }
34+
//
35+
// @Test
36+
// public void test_getApiKey_keySet() {
37+
// String actualKey = "test";
38+
// System.setProperty(Constants.API_KEY_SYSTEM_PROP, actualKey);
39+
//
40+
// String foundKey = checker.getApiKey();
41+
// assertEquals("API key did not match expected value.", actualKey, foundKey);
42+
// }
5643

5744
/******************************************************* isTranscriptReady *******************************************************/
5845

0 commit comments

Comments
 (0)