File: TestWsWebSocketContainerGetOpenSessions.java

package info (click to toggle)
tomcat11 11.0.18-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,520 kB
  • sloc: java: 370,500; xml: 56,763; jsp: 4,787; sh: 1,304; perl: 324; makefile: 25; ansic: 14
file content (391 lines) | stat: -rw-r--r-- 12,600 bytes parent folder | download | duplicates (9)
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.tomcat.websocket;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import jakarta.servlet.ServletContextEvent;
import jakarta.websocket.ClientEndpointConfig;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.Endpoint;
import jakarta.websocket.EndpointConfig;
import jakarta.websocket.MessageHandler;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
import jakarta.websocket.server.ServerContainer;
import jakarta.websocket.server.ServerEndpoint;
import jakarta.websocket.server.ServerEndpointConfig;

import org.junit.Assert;
import org.junit.Test;

import org.apache.catalina.Context;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.websocket.server.Constants;
import org.apache.tomcat.websocket.server.WsContextListener;

/*
 * This method is split out into a separate class to make it easier to track the
 * various permutations and combinations of client and server endpoints.
 *
 * Each test uses 2 client endpoint and 2 server endpoints with each client
 * connecting to each server for a total of four connections (note sometimes
 * the two clients and/or the two servers will be the same).
 */
public class TestWsWebSocketContainerGetOpenSessions extends WebSocketBaseTest {

    @Test
    public void testClientAClientAPojoAPojoA() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointA();

        doTest(client1, client2, "/pojoA", "/pojoA", 2, 2, 4, 4);
    }


    @Test
    public void testClientAClientBPojoAPojoA() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointB();

        doTest(client1, client2, "/pojoA", "/pojoA", 2, 2, 4, 4);
    }


    @Test
    public void testClientAClientAPojoAPojoB() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointA();

        doTest(client1, client2, "/pojoA", "/pojoB", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientBPojoAPojoB() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointB();

        doTest(client1, client2, "/pojoA", "/pojoB", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientAProgAProgA() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointA();

        doTest(client1, client2, "/progA", "/progA", 2, 2, 4, 4);
    }


    @Test
    public void testClientAClientBProgAProgA() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointB();

        doTest(client1, client2, "/progA", "/progA", 2, 2, 4, 4);
    }


    @Test
    public void testClientAClientAProgAProgB() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointA();

        doTest(client1, client2, "/progA", "/progB", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientBProgAProgB() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointB();

        doTest(client1, client2, "/progA", "/progB", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientAPojoAProgA() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointA();

        doTest(client1, client2, "/pojoA", "/progA", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientBPojoAProgA() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointB();

        doTest(client1, client2, "/pojoA", "/progA", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientAPojoAProgB() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointA();

        doTest(client1, client2, "/pojoA", "/progB", 2, 2, 2, 2);
    }


    @Test
    public void testClientAClientBPojoAProgB() throws Exception {
        Endpoint client1 = new ClientEndpointA();
        Endpoint client2 = new ClientEndpointB();

        doTest(client1, client2, "/pojoA", "/progB", 2, 2, 2, 2);
    }


    private void doTest(Endpoint client1, Endpoint client2, String server1, String server2, int client1Count,
            int client2Count, int server1Count, int server2Count) throws Exception {
        Tracker.reset();
        Tomcat tomcat = getTomcatInstance();
        // No file system docBase required
        Context ctx = getProgrammaticRootContext();
        ctx.addApplicationListener(Config.class.getName());
        Tomcat.addServlet(ctx, "default", new DefaultServlet());
        ctx.addServletMappingDecoded("/", "default");

        tomcat.start();

        WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

        Session sClient1Server1 = createSession(wsContainer, client1, "client1", server1);
        Session sClient1Server2 = createSession(wsContainer, client1, "client1", server2);
        Session sClient2Server1 = createSession(wsContainer, client2, "client2", server1);
        Session sClient2Server2 = createSession(wsContainer, client2, "client2", server2);


        int delayCount = 0;
        // Wait for up to 20s for this to complete. It should be a lot faster
        // but some CI systems get be slow at times.
        while (Tracker.getUpdateCount() < 8 && delayCount < 400) {
            Thread.sleep(50);
            delayCount++;
        }

        Assert.assertTrue(Tracker.dump(), Tracker.checkRecord("client1", client1Count));
        Assert.assertTrue(Tracker.dump(), Tracker.checkRecord("client2", client2Count));
        // Note: need to strip leading '/' from path
        Assert.assertTrue(Tracker.dump(), Tracker.checkRecord(server1.substring(1), server1Count));
        Assert.assertTrue(Tracker.dump(), Tracker.checkRecord(server2.substring(1), server2Count));

        sClient1Server1.close();
        sClient1Server2.close();
        sClient2Server1.close();
        sClient2Server2.close();
    }


    private Session createSession(WebSocketContainer wsContainer, Endpoint client, String clientName, String server)
            throws DeploymentException, IOException, URISyntaxException {

        Session s = wsContainer.connectToServer(client, ClientEndpointConfig.Builder.create().build(),
                new URI("ws://localhost:" + getPort() + server));
        Tracker.addRecord(clientName, s.getOpenSessions().size());
        s.getBasicRemote().sendText("X");
        return s;
    }


    public static class Config extends WsContextListener {

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            super.contextInitialized(sce);
            ServerContainer sc = (ServerContainer) sce.getServletContext()
                    .getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

            try {
                sc.addEndpoint(PojoEndpointA.class);
                sc.addEndpoint(PojoEndpointB.class);
                sc.addEndpoint(ServerEndpointConfig.Builder.create(ServerEndpointA.class, "/progA").build());
                sc.addEndpoint(ServerEndpointConfig.Builder.create(ServerEndpointB.class, "/progB").build());
            } catch (DeploymentException e) {
                throw new IllegalStateException(e);
            }
        }
    }


    public abstract static class PojoEndpointBase {

        @OnMessage
        public void onMessage(@SuppressWarnings("unused") String msg, Session session) {
            Tracker.addRecord(getTrackingName(), session.getOpenSessions().size());
        }

        protected abstract String getTrackingName();
    }


    @ServerEndpoint("/pojoA")
    public static class PojoEndpointA extends PojoEndpointBase {

        @Override
        protected String getTrackingName() {
            return "pojoA";
        }
    }


    @ServerEndpoint("/pojoB")
    public static class PojoEndpointB extends PojoEndpointBase {

        @Override
        protected String getTrackingName() {
            return "pojoB";
        }
    }


    public abstract static class ServerEndpointBase extends Endpoint {

        @Override
        public void onOpen(Session session, EndpointConfig config) {
            session.addMessageHandler(new TrackerMessageHandler(session, getTrackingName()));
        }

        protected abstract String getTrackingName();
    }


    public static final class ServerEndpointA extends ServerEndpointBase {

        @Override
        protected String getTrackingName() {
            return "progA";
        }
    }


    public static final class ServerEndpointB extends ServerEndpointBase {

        @Override
        protected String getTrackingName() {
            return "progB";
        }
    }


    public static final class TrackerMessageHandler implements MessageHandler.Whole<String> {

        private final Session session;
        private final String trackingName;

        public TrackerMessageHandler(Session session, String trackingName) {
            this.session = session;
            this.trackingName = trackingName;
        }

        @Override
        public void onMessage(String message) {
            Tracker.addRecord(trackingName, session.getOpenSessions().size());
        }
    }


    public abstract static class ClientEndpointBase extends Endpoint {

        @Override
        public void onOpen(Session session, EndpointConfig config) {
            // NO-OP
        }

        @Override
        public void onClose(Session session, CloseReason closeReason) {
            // NO-OP
        }

        protected abstract String getTrackingName();
    }


    public static final class ClientEndpointA extends ClientEndpointBase {

        @Override
        protected String getTrackingName() {
            return "clientA";
        }
    }


    public static final class ClientEndpointB extends ClientEndpointBase {

        @Override
        protected String getTrackingName() {
            return "clientB";
        }
    }


    public static class Tracker {

        private static final Map<String, Integer> records = new HashMap<>();
        private static int updateCount = 0;

        public static synchronized void addRecord(String key, int count) {
            // Need to avoid out of order updates to the Map. If out of order
            // updates occur, keep the one with the highest count.
            Integer oldCount = records.get(key);
            if (oldCount == null || oldCount.intValue() < count) {
                records.put(key, Integer.valueOf(count));
            }
            updateCount++;
        }

        public static synchronized boolean checkRecord(String key, int expectedCount) {
            Integer actualCount = records.get(key);
            if (actualCount == null) {
                if (expectedCount == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return actualCount.intValue() == expectedCount;
            }
        }

        public static synchronized int getUpdateCount() {
            return updateCount;
        }

        public static synchronized void reset() {
            records.clear();
            updateCount = 0;
        }

        public static synchronized String dump() {
            return records.toString();
        }
    }
}