Last active
May 10, 2019 05:19
-
-
Save ZhouMeichen/8553c134f81412bcc2ea3d2acfa735cc to your computer and use it in GitHub Desktop.
Implement JMeter Java Request to test websocket API (transmit audio data)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.io.UnsupportedEncodingException; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
public class Sha1 { | |
private static final String HEX_DIGITS = "0123456789abcdef"; | |
private static final int BYTE_MSK = 0xFF; | |
private static final int HEX_DIGIT_BITS = 4; | |
private static final int HEX_DIGIT_MASK = 0xF; | |
private static String toHexString(final byte[] byteArray) { | |
StringBuilder sb = new StringBuilder(byteArray.length * 2); | |
for (int i = 0; i < byteArray.length; i++) { | |
int b = byteArray[i] & BYTE_MSK; | |
sb.append(HEX_DIGITS.charAt(b >>> HEX_DIGIT_BITS)).append( | |
HEX_DIGITS.charAt(b & HEX_DIGIT_MASK)); | |
} | |
return sb.toString(); | |
} | |
public String generate(String str){ | |
String result=null; | |
try { | |
MessageDigest msgDgst = MessageDigest.getInstance("SHA-1"); | |
byte[] sha1hash; | |
sha1hash = msgDgst.digest(str.getBytes("UTF-8")); | |
result = toHexString(sha1hash); | |
} catch (NoSuchAlgorithmException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
catch (UnsupportedEncodingException e1) { | |
// TODO Auto-generated catch block | |
e1.printStackTrace(); | |
} | |
return result; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import org.apache.jmeter.config.Arguments; | |
import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient; | |
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext; | |
import org.apache.jmeter.samplers.SampleResult; | |
import org.apache.jorphan.logging.LoggingManager; | |
import org.apache.log.Logger; | |
import org.glassfish.tyrus.client.ClientManager; | |
import org.json.JSONObject; | |
import javax.websocket.*; | |
import java.io.IOException; | |
import java.io.RandomAccessFile; | |
import java.net.URI; | |
import java.nio.ByteBuffer; | |
import java.util.Date; | |
import java.util.concurrent.CountDownLatch; | |
import java.util.concurrent.TimeUnit; | |
@ClientEndpoint | |
public class WebsocketRequest implements JavaSamplerClient | |
{ | |
private static String ws_uri; | |
private static String ws_audio; | |
private static int ws_read_size; | |
private static String ws_rank; | |
private static String ws_precision; | |
private static String ws_robust; | |
private static String ws_textMode; | |
private static String ws_use_contispeech; | |
private static String ws_use_only_conti; | |
private static String ws_ext_subitem_rank4; | |
private static String ws_ext_word_details; | |
private static String ws_ext_phn_details; | |
private static String ws_ext_cur_snt; | |
private static String ws_appkey; | |
private static String ws_secretkey; | |
private static String ws_ref; | |
private static Long ws_timeout; | |
private static String response_message; | |
private static CountDownLatch latch; | |
private static final Logger log = LoggingManager.getLoggerForClass(); | |
private static String coretype; | |
private static String res; | |
private static String audiotype; | |
private static String timestamp; | |
private static String sig; | |
private static Double sv = 0.0; | |
public Arguments getDefaultParameters() { | |
Arguments params = new Arguments(); | |
params.addArgument("uri","ws://10.0.200.166:8090/en.word.score?e=0&t=0"); | |
params.addArgument("audio","test.wav"); | |
params.addArgument("read_size(b)","1024"); | |
params.addArgument("appkey","xxxxxxxxx"); | |
params.addArgument("secretkey","xxxxxxxxx"); | |
params.addArgument("reftext","\"jmeter\""); | |
params.addArgument("rank","100"); | |
params.addArgument("precision","0.5"); | |
params.addArgument("robust","0"); | |
params.addArgument("textMode","0"); | |
params.addArgument("use_contispeech","0"); | |
params.addArgument("use_only_conti","0"); | |
params.addArgument("ext_subitem_rank4","0"); | |
params.addArgument("ext_word_details","1"); | |
params.addArgument("ext_phn_details","1"); | |
params.addArgument("ext_cur_snt","0"); | |
params.addArgument("timeout(s)","5"); | |
return params; | |
} | |
public void setupTest(JavaSamplerContext context) { | |
ws_uri = context.getParameter("uri"); | |
ws_appkey = context.getParameter("appkey"); | |
ws_secretkey = context.getParameter("secretkey"); | |
ws_audio = context.getParameter("audio"); | |
ws_read_size = (int) Long.parseLong(context.getParameter("read_size(b)")); | |
ws_ref = context.getParameter("reftext"); | |
ws_rank = context.getParameter("rank"); | |
ws_precision = context.getParameter("precision"); | |
ws_robust = context.getParameter("robust"); | |
ws_textMode = context.getParameter("textMode"); | |
ws_use_contispeech = context.getParameter("use_contispeech"); | |
ws_use_only_conti = context.getParameter("use_only_conti"); | |
ws_ext_subitem_rank4 = context.getParameter("ext_subitem_rank4"); | |
ws_ext_word_details = context.getParameter("ext_word_details"); | |
ws_ext_phn_details = context.getParameter("ext_phn_details"); | |
ws_ext_cur_snt = context.getParameter("ext_cur_snt"); | |
ws_timeout = Long.parseLong(context.getParameter("timeout(s)")); | |
getCoretype(); | |
getRes(); | |
getAudioType(); | |
getTimestamp(); | |
getSig(); | |
} | |
public void teardownTest(JavaSamplerContext arg0) { | |
// TODO Auto-generated method stub | |
} | |
public SampleResult runTest(JavaSamplerContext javaSamplerContext) { | |
SampleResult rv = new SampleResult(); | |
rv.sampleStart(); | |
latch = new CountDownLatch(1); | |
ClientManager client = ClientManager.createClient(); | |
try { | |
client.connectToServer(WebsocketRequest.class, new URI(ws_uri)); | |
latch.await(ws_timeout, TimeUnit.SECONDS); | |
} catch (Throwable e) { | |
throw new RuntimeException(e); | |
} | |
rv.setSuccessful(true); | |
rv.setResponseMessage(response_message); | |
rv.setResponseCode("200"); | |
if (response_message!=null){ | |
rv.setResponseData(response_message.getBytes()); | |
} | |
rv.sampleEnd(); | |
return rv; | |
} | |
@OnOpen | |
public void onOpen(Session session) { | |
log.info("Connected ... " + session.getId()); | |
try { | |
String cfg = "{\"cmd\": \"connect\", \"param\": {\"coreProvideType\": \"cloud\",\"app\": {\"applicationId\": \""+ws_appkey+"\", \"sig\":\""+sig+"\", \"timestamp\": \""+timestamp+"\"},\"sdk\": {\"version\": \"0x01050200\", \"source\": \"0x06\", \"protocol\": \"yyyyyyyy\"}}}"; | |
session.getBasicRemote().sendText(cfg); | |
String param = "{\"cmd\": \"start\",\"coreProvideType\": \"cloud\",\"param\": {\"app\": {\"applicationId\": \""+ws_appkey+"\",\"userId\": \"jmeter\",\"timestamp\":\""+timestamp+"\",\"sig\": \""+sig+"\"},\"sdk\": {\"version\": \"\",\"source\": \"\",\"protocol\": \"yyyyyyyy\"},\"audio\":{\"channel\": 1,\"sampleBytes\":2,\"audioType\": \""+audiotype+"\",\"sampleRate\":16000},\"request\": {\"tokenId\": \"hhhhhhhhhhh\",\"isT2p\":\"True\",\"textMode\":"+ws_textMode+",\"coreType\":\""+coretype+"\",\"res\":\""+res+"\",\"rank\":"+ws_rank+",\"precision\":"+ws_precision+",\"refText\":"+ws_ref+",\"robust\":"+ws_robust+",\"use_contispeech\":"+ws_use_contispeech+",\"contispeech\":{\"use_only_conti\":"+ws_use_only_conti+"},\"client_params\":{\"ext_subitem_rank4\":"+ws_ext_subitem_rank4+",\"ext_word_details\":"+ws_ext_word_details+",\"ext_phn_details\":"+ws_ext_phn_details+",\"ext_cur_snt\":"+ws_ext_cur_snt+"}}}}"; | |
session.getBasicRemote().sendText(param); | |
byte[] data = new byte[ws_read_size]; | |
try { | |
RandomAccessFile raf = new RandomAccessFile(ws_audio,"r"); | |
if(ws_audio.contains(".wav")){ | |
raf.seek(44); | |
} | |
while(true){ | |
int rsize = raf.read(data,0,data.length); | |
if (rsize < 0){ | |
break; | |
} | |
session.getBasicRemote().sendBinary(ByteBuffer.wrap(data),false); | |
} | |
raf.close(); | |
} catch(IOException e){ | |
e.printStackTrace(); | |
} | |
session.getBasicRemote().sendText(""); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
@OnMessage | |
public String onMessage(String message, Session session) { | |
log.info("Received ... " + message + " on session " + session.getId()) ; | |
response_message = message; | |
calculate(session); | |
try { | |
session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,"")); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return response_message; | |
} | |
@OnClose | |
public void onClose(Session session, CloseReason closeReason) { | |
log.info(String.format("Session %s close because of %s", session.getId(), closeReason)); | |
} | |
private void calculate(Session session){ | |
int systime=0; | |
int wavetime=0; | |
if ((response_message != null) && (!response_message.contains("errId"))){ | |
JSONObject json = new JSONObject(response_message); | |
systime = json.getJSONObject("result").getInt("systime"); | |
wavetime = json.getJSONObject("result").getInt("wavetime"); | |
if (wavetime != 0){ | |
sv = (double) systime/(double) wavetime; | |
} | |
} | |
log.info("Calculated ... " + "(sv:"+sv+")" + " on session " + session.getId()); | |
} | |
private void getSig(){ | |
Sha1 sh = new Sha1(); | |
sig = sh.generate(ws_appkey+timestamp+ws_secretkey); | |
} | |
private void getTimestamp(){ | |
Date date = new Date(); | |
timestamp=String.format("%ts", date)+"."+String.format("%tQ", date).split(String.format("%ts", date))[1]; | |
} | |
private void getCoretype(){ | |
coretype = ws_uri.split("/")[3].split("[?]")[0]; | |
} | |
private void getRes(){ | |
String[] core = ws_uri.split("/"); | |
if (core.length == 4){ | |
res = ""; | |
}else{ | |
res = core[4].split("[?]")[0]; | |
} | |
} | |
private void getAudioType(){ | |
String[] audio = ws_audio.split("[.]"); | |
audiotype = audio[audio.length-1]; | |
} | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Arguments args0 = new Arguments(); | |
args0.addArgument("uri","ws://10.0.200.166:8090/en.sent.score?e=0&t=0"); | |
args0.addArgument("audio","test.wav"); | |
args0.addArgument("read_size(b)","204600"); | |
args0.addArgument("appkey","xxxxxxxxx"); | |
args0.addArgument("secretkey","xxxxxxxxx"); | |
args0.addArgument("reftext","\"The trees there are very famous.\""); | |
args0.addArgument("rank","100"); | |
args0.addArgument("precision","0.5"); | |
args0.addArgument("robust","0"); | |
args0.addArgument("textMode","0"); | |
args0.addArgument("use_contispeech","0"); | |
args0.addArgument("use_only_conti","0"); | |
args0.addArgument("ext_subitem_rank4","0"); | |
args0.addArgument("ext_word_details","1"); | |
args0.addArgument("ext_phn_details","1"); | |
args0.addArgument("ext_cur_snt","0"); | |
args0.addArgument("timeout(s)","3"); | |
WebsocketRequest wr = new WebsocketRequest(); | |
JavaSamplerContext context = new JavaSamplerContext(args0); | |
wr.setupTest(context); | |
wr.runTest(context); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment