-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathServiceSocket.java
More file actions
287 lines (245 loc) · 10.5 KB
/
ServiceSocket.java
File metadata and controls
287 lines (245 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JMeter.plugins.functional.samplers.websocket;
import java.io.IOException;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.log.Logger;
import java.util.regex.Pattern;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jorphan.logging.LoggingManager;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketFrame;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.api.extensions.Frame;
import org.eclipse.jetty.websocket.client.WebSocketClient;
/**
*
* @author Maciej Zaleskisgsdgsdg
*/
@WebSocket(maxTextMessageSize = 256 * 1024 * 1024)
public class ServiceSocket {
protected final WebSocketSampler parent;
protected WebSocketClient client;
private static final Logger log = LoggingManager.getLoggerForClass();
protected Deque<String> responeBacklog = new LinkedList<String>();
protected Integer error = 0;
protected StringBuffer logMessage = new StringBuffer();
protected CountDownLatch openLatch = new CountDownLatch(1);
protected CountDownLatch closeLatch = new CountDownLatch(1);
protected Session session = null;
protected String responsePattern;
protected String disconnectPattern;
protected int messageCounter = 1;
protected Pattern responseExpression;
protected Pattern disconnectExpression;
protected boolean connected = false;
public ServiceSocket(WebSocketSampler parent, WebSocketClient client) {
this.parent = parent;
this.client = client;
//Evaluate response matching patterns in case thay contain JMeter variables (i.e. ${var})
responsePattern = new CompoundVariable(parent.getResponsePattern()).execute();
disconnectPattern = new CompoundVariable(parent.getCloseConncectionPattern()).execute();
logMessage.append("\n\n[Execution Flow]\n");
logMessage.append(" - Opening new connection\n");
initializePatterns();
}
@OnWebSocketMessage
public void onMessage(String msg) {
synchronized (parent) {
log.debug("Received message: " + msg);
String length = " (" + msg.length() + " bytes)";
logMessage.append(" - Received message #").append(messageCounter).append(length);
addResponseMessage("[Message " + (messageCounter++) + "]\n" + msg + "\n\n");
if (responseExpression == null || responseExpression.matcher(msg).find()) {
logMessage.append("; matched response pattern").append("\n");
closeLatch.countDown();
} else if (!disconnectPattern.isEmpty() && disconnectExpression.matcher(msg).find()) {
logMessage.append("; matched connection close pattern").append("\n");
closeLatch.countDown();
close(StatusCode.NORMAL, "JMeter closed session.");
} else {
logMessage.append("; didn't match any pattern").append("\n");
}
}
}
@OnWebSocketFrame
public void onFrame(Frame frame) {
synchronized (parent) {
log.debug("Received frame: " + frame.getPayload() + " "
+ frame.getType().name());
String length = " (" + frame.getPayloadLength() + " bytes)";
logMessage.append(" - Received frame #").append(messageCounter)
.append(length);
String frameTxt = new String(frame.getPayload().array());
addResponseMessage("[Frame " + (messageCounter++) + "]\n"
+ frameTxt + "\n\n");
if (responseExpression == null
|| responseExpression.matcher(frameTxt).find()) {
logMessage.append("; matched response pattern").append("\n");
closeLatch.countDown();
} else if (!disconnectPattern.isEmpty()
&& disconnectExpression.matcher(frameTxt).find()) {
logMessage.append("; matched connection close pattern").append(
"\n");
closeLatch.countDown();
close(StatusCode.NORMAL, "JMeter closed session.");
} else {
logMessage.append("; didn't match any pattern").append("\n");
}
}
}
@OnWebSocketConnect
public void onOpen(Session session) {
logMessage.append(" - WebSocket conection has been opened").append("\n");
log.debug("Connect " + session.isOpen());
this.session = session;
connected = true;
openLatch.countDown();
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
if (statusCode != 1000) {
log.error("Disconnect " + statusCode + ": " + reason);
logMessage.append(" - WebSocket conection closed unexpectedly by the server: [").append(statusCode).append("] ").append(reason).append("\n");
error = statusCode;
} else {
logMessage.append(" - WebSocket conection has been successfully closed by the server").append("\n");
log.debug("Disconnect " + statusCode + ": " + reason);
}
//Notify connection opening and closing latches of the closed connection
openLatch.countDown();
closeLatch.countDown();
connected = false;
}
/**
* @return response message made of messages saved in the responeBacklog cache
*/
public String getResponseMessage() {
String responseMessage = "";
//Iterate through response messages saved in the responeBacklog cache
Iterator<String> iterator = responeBacklog.iterator();
while (iterator.hasNext()) {
responseMessage += iterator.next();
}
return responseMessage;
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
logMessage.append(" - Waiting for messages for ").append(duration).append(" ").append(unit.toString()).append("\n");
boolean res = this.closeLatch.await(duration, unit);
if (!parent.isStreamingConnection()) {
close(StatusCode.NORMAL, "JMeter closed session.");
} else {
logMessage.append(" - Leaving streaming connection open").append("\n");
}
return res;
}
public boolean awaitOpen(int duration, TimeUnit unit) throws InterruptedException {
logMessage.append(" - Waiting for the server connection for ").append(duration).append(" ").append(unit.toString()).append("\n");
boolean res = this.openLatch.await(duration, unit);
if (connected) {
logMessage.append(" - Connection established").append("\n");
} else {
logMessage.append(" - Cannot connect to the remote server").append("\n");
}
return res;
}
/**
* @return the session
*/
public Session getSession() {
return session;
}
public void sendMessage(String message) throws IOException {
session.getRemote().sendString(message);
}
public void close() {
close(StatusCode.NORMAL, "JMeter closed session.");
}
public void close(int statusCode, String statusText) {
//Closing WebSocket session
if (session != null) {
session.close(statusCode, statusText);
logMessage.append(" - WebSocket session closed by the client").append("\n");
} else {
logMessage.append(" - WebSocket session wasn't started (...that's odd)").append("\n");
}
//Stoping WebSocket client; thanks m0ro
try {
client.stop();
logMessage.append(" - WebSocket client closed by the client").append("\n");
} catch (Exception e) {
logMessage.append(" - WebSocket client wasn't started (...that's odd)").append("\n");
}
}
/**
* @return the error
*/
public Integer getError() {
return error;
}
/**
* @return the logMessage
*/
public String getLogMessage() {
logMessage.append("\n\n[Variables]\n");
logMessage.append(" - Message count: ").append(messageCounter - 1).append("\n");
return logMessage.toString();
}
public void log(String message) {
logMessage.append(message);
}
protected void initializePatterns() {
try {
logMessage.append(" - Using response message pattern \"").append(responsePattern).append("\"\n");
responseExpression = (responsePattern != null || !responsePattern.isEmpty()) ? Pattern.compile(responsePattern) : null;
} catch (Exception ex) {
logMessage.append(" - Invalid response message regular expression pattern: ").append(ex.getLocalizedMessage()).append("\n");
log.error("Invalid response message regular expression pattern: " + ex.getLocalizedMessage());
responseExpression = null;
}
try {
logMessage.append(" - Using disconnect pattern \"").append(disconnectPattern).append("\"\n");
disconnectExpression = (disconnectPattern != null || !disconnectPattern.isEmpty()) ? Pattern.compile(disconnectPattern) : null;
} catch (Exception ex) {
logMessage.append(" - Invalid disconnect regular expression pattern: ").append(ex.getLocalizedMessage()).append("\n");
log.error("Invalid disconnect regular regular expression pattern: " + ex.getLocalizedMessage());
disconnectExpression = null;
}
}
/**
* @return the connected
*/
public boolean isConnected() {
return connected;
}
public void initialize() {
logMessage = new StringBuffer();
logMessage.append("\n\n[Execution Flow]\n");
logMessage.append(" - Reusing exising connection\n");
error = 0;
this.closeLatch = new CountDownLatch(1);
}
private void addResponseMessage(String message) {
int messageBacklog;
try {
messageBacklog = Integer.parseInt(parent.getMessageBacklog());
} catch (Exception ex) {
logMessage.append(" - Message backlog value not set; using default ").append(WebSocketSampler.MESSAGE_BACKLOG_COUNT).append("\n");
messageBacklog = WebSocketSampler.MESSAGE_BACKLOG_COUNT;
}
while (responeBacklog.size() >= messageBacklog) {
responeBacklog.poll();
}
responeBacklog.add(message);
}
}