0
# Monitoring and Statistics
1
2
Comprehensive monitoring system with application-level and request-level event handling, statistics collection, JMX integration, and performance metrics. Provides detailed insights into application performance, resource usage, and operational behavior.
3
4
## Capabilities
5
6
### Event System
7
8
Application and request event handling for monitoring Jersey server operations and performance.
9
10
```java { .api }
11
/**
12
* Application event interface representing application-level events.
13
*/
14
public interface ApplicationEvent {
15
16
/**
17
* Event type enumeration for application events.
18
*/
19
enum Type {
20
INITIALIZATION_START,
21
INITIALIZATION_FINISHED,
22
DESTROY_FINISHED,
23
RELOAD_FINISHED
24
}
25
26
/**
27
* Get the event type.
28
* @return Event type
29
*/
30
Type getType();
31
32
/**
33
* Get the resource config associated with this event.
34
* @return ResourceConfig instance
35
*/
36
ResourceConfig getResourceConfig();
37
}
38
39
/**
40
* Application event listener for monitoring application lifecycle.
41
*/
42
public interface ApplicationEventListener {
43
44
/**
45
* Called when an application event occurs.
46
* @param event Application event
47
*/
48
void onEvent(ApplicationEvent event);
49
50
/**
51
* Called when a request event occurs, returns request event listener.
52
* @param requestEvent Initial request event
53
* @return RequestEventListener for this request or null
54
*/
55
RequestEventListener onRequest(RequestEvent requestEvent);
56
}
57
58
/**
59
* Request event interface representing request-level events.
60
*/
61
public interface RequestEvent {
62
63
/**
64
* Event type enumeration for request events.
65
*/
66
enum Type {
67
START,
68
MATCHING_START,
69
MATCHING_FINISHED,
70
REQUEST_MATCHED,
71
REQUEST_FILTERED,
72
RESOURCE_METHOD_START,
73
RESOURCE_METHOD_FINISHED,
74
RESP_FILTERS_START,
75
RESP_FILTERS_FINISHED,
76
ON_EXCEPTION,
77
FINISHED,
78
EXCEPTION_MAPPING_FINISHED
79
}
80
81
/**
82
* Get the event type.
83
* @return Event type
84
*/
85
Type getType();
86
87
/**
88
* Get the container request.
89
* @return ContainerRequest for this event
90
*/
91
ContainerRequest getContainerRequest();
92
93
/**
94
* Get the container response.
95
* @return ContainerResponse for this event or null if not available
96
*/
97
ContainerResponse getContainerResponse();
98
99
/**
100
* Get exception if this is an exception event.
101
* @return Exception or null
102
*/
103
Throwable getException();
104
}
105
106
/**
107
* Request event listener for monitoring individual request processing.
108
*/
109
public interface RequestEventListener {
110
111
/**
112
* Called when a request event occurs.
113
* @param event Request event
114
*/
115
void onEvent(RequestEvent event);
116
}
117
```
118
119
**Usage Examples:**
120
121
```java
122
import org.glassfish.jersey.server.monitoring.*;
123
import java.util.concurrent.atomic.AtomicLong;
124
import java.util.concurrent.ConcurrentHashMap;
125
126
// Custom application event listener
127
public class CustomApplicationEventListener implements ApplicationEventListener {
128
129
private final AtomicLong requestCounter = new AtomicLong();
130
private final Map<String, AtomicLong> resourceCallCounts = new ConcurrentHashMap<>();
131
132
@Override
133
public void onEvent(ApplicationEvent event) {
134
switch (event.getType()) {
135
case INITIALIZATION_START:
136
System.out.println("Jersey application initializing...");
137
break;
138
case INITIALIZATION_FINISHED:
139
System.out.println("Jersey application initialized successfully");
140
break;
141
case DESTROY_FINISHED:
142
System.out.println("Jersey application destroyed");
143
break;
144
case RELOAD_FINISHED:
145
System.out.println("Jersey application reloaded");
146
break;
147
}
148
}
149
150
@Override
151
public RequestEventListener onRequest(RequestEvent requestEvent) {
152
requestCounter.incrementAndGet();
153
154
return new RequestEventListener() {
155
private long startTime;
156
157
@Override
158
public void onEvent(RequestEvent event) {
159
switch (event.getType()) {
160
case START:
161
startTime = System.currentTimeMillis();
162
break;
163
164
case REQUEST_MATCHED:
165
// Track resource usage
166
ContainerRequest request = event.getContainerRequest();
167
String path = request.getPath(false);
168
resourceCallCounts.computeIfAbsent(path, k -> new AtomicLong()).incrementAndGet();
169
break;
170
171
case FINISHED:
172
long duration = System.currentTimeMillis() - startTime;
173
System.out.println("Request completed in " + duration + "ms");
174
break;
175
176
case ON_EXCEPTION:
177
Throwable exception = event.getException();
178
System.err.println("Request exception: " + exception.getMessage());
179
break;
180
}
181
}
182
};
183
}
184
}
185
186
// Register the listener
187
ResourceConfig config = new ResourceConfig()
188
.packages("com.example.resources")
189
.register(CustomApplicationEventListener.class);
190
```
191
192
### Statistics Collection
193
194
Core monitoring statistics interfaces providing detailed performance and usage metrics.
195
196
```java { .api }
197
/**
198
* Core monitoring statistics interface providing access to all monitoring data.
199
*/
200
public interface MonitoringStatistics {
201
202
/**
203
* Get request execution statistics.
204
* @return ExecutionStatistics for all requests
205
*/
206
ExecutionStatistics getRequestStatistics();
207
208
/**
209
* Get response statistics.
210
* @return ResponseStatistics for all responses
211
*/
212
ResponseStatistics getResponseStatistics();
213
214
/**
215
* Get URI-specific statistics.
216
* @return Map of URI patterns to ResourceStatistics
217
*/
218
Map<String, ResourceStatistics> getUriStatistics();
219
220
/**
221
* Get exception mapper statistics.
222
* @return Map of exception types to ExceptionMapperStatistics
223
*/
224
Map<Class<?>, ExceptionMapperStatistics> getExceptionMapperStatistics();
225
226
/**
227
* Get monitoring statistics snapshot timestamp.
228
* @return Timestamp when statistics were captured
229
*/
230
Date getSnapshot();
231
}
232
233
/**
234
* Execution statistics providing timing and performance metrics.
235
*/
236
public interface ExecutionStatistics {
237
238
/**
239
* Get time window size for statistics.
240
* @return Time window size
241
*/
242
long getTimeWindowSize();
243
244
/**
245
* Get time window size unit.
246
* @return TimeUnit for the time window
247
*/
248
TimeUnit getTimeWindowSizeUnit();
249
250
/**
251
* Get time window statistics.
252
* @return TimeWindowStatistics for the current window
253
*/
254
TimeWindowStatistics getTimeWindowStatistics();
255
256
/**
257
* Get last finished execution timestamp.
258
* @return Timestamp of last finished execution
259
*/
260
Date getLastStartTime();
261
}
262
263
/**
264
* Time window statistics providing metrics over a specific time period.
265
*/
266
public interface TimeWindowStatistics {
267
268
/**
269
* Get time window size.
270
* @return Time window size in milliseconds
271
*/
272
long getTimeWindow();
273
274
/**
275
* Get minimum execution time in the window.
276
* @return Minimum execution time in milliseconds
277
*/
278
long getMinimumDuration();
279
280
/**
281
* Get maximum execution time in the window.
282
* @return Maximum execution time in milliseconds
283
*/
284
long getMaximumDuration();
285
286
/**
287
* Get average execution time in the window.
288
* @return Average execution time in milliseconds
289
*/
290
long getAverageDuration();
291
292
/**
293
* Get total number of requests in the window.
294
* @return Request count
295
*/
296
long getRequestCount();
297
298
/**
299
* Get requests per second rate.
300
* @return Requests per second
301
*/
302
double getRequestsPerSecond();
303
}
304
```
305
306
### Resource Statistics
307
308
Detailed statistics for individual resources and their methods.
309
310
```java { .api }
311
/**
312
* Resource-level statistics providing metrics for individual resources.
313
*/
314
public interface ResourceStatistics {
315
316
/**
317
* Get execution statistics for this resource.
318
* @return ExecutionStatistics for all resource method calls
319
*/
320
ExecutionStatistics getRequestExecutionStatistics();
321
322
/**
323
* Get resource method statistics.
324
* @return Map of method signatures to ResourceMethodStatistics
325
*/
326
Map<String, ResourceMethodStatistics> getResourceMethodStatistics();
327
328
/**
329
* Get resource path.
330
* @return Resource path pattern
331
*/
332
String getPath();
333
}
334
335
/**
336
* Resource method statistics providing method-level performance metrics.
337
*/
338
public interface ResourceMethodStatistics {
339
340
/**
341
* Get execution statistics for this method.
342
* @return ExecutionStatistics for this specific method
343
*/
344
ExecutionStatistics getRequestExecutionStatistics();
345
346
/**
347
* Get HTTP method.
348
* @return HTTP method (GET, POST, etc.)
349
*/
350
String getMethod();
351
352
/**
353
* Get method path within the resource.
354
* @return Method-specific path pattern
355
*/
356
String getPath();
357
358
/**
359
* Get total invocation count.
360
* @return Number of times this method was invoked
361
*/
362
long getInvocationCount();
363
}
364
```
365
366
### Response Statistics
367
368
HTTP response statistics and metrics.
369
370
```java { .api }
371
/**
372
* Response statistics providing HTTP response metrics.
373
*/
374
public interface ResponseStatistics {
375
376
/**
377
* Get response code statistics.
378
* @return Map of status codes to their occurrence counts
379
*/
380
Map<Integer, Long> getResponseCodes();
381
382
/**
383
* Get count for specific response code.
384
* @param responseCode HTTP response code
385
* @return Count of responses with this code
386
*/
387
Long getResponseCodeCount(int responseCode);
388
389
/**
390
* Get total response count.
391
* @return Total number of responses
392
*/
393
long getTotalResponseCount();
394
395
/**
396
* Get last response timestamp.
397
* @return Timestamp of last response
398
*/
399
Date getLastResponseTime();
400
}
401
```
402
403
### JMX Integration
404
405
JMX MBean interfaces for monitoring through standard JMX tools.
406
407
```java { .api }
408
/**
409
* Application MXBean for JMX monitoring of application-level metrics.
410
*/
411
public interface ApplicationMXBean {
412
413
/**
414
* Get application name.
415
* @return Application name
416
*/
417
String getApplicationName();
418
419
/**
420
* Get application class name.
421
* @return Fully qualified application class name
422
*/
423
String getApplicationClass();
424
425
/**
426
* Get initialization timestamp.
427
* @return Application initialization timestamp
428
*/
429
Date getStartTime();
430
431
/**
432
* Get registered resource classes.
433
* @return Set of resource class names
434
*/
435
Set<String> getRegisteredClasses();
436
437
/**
438
* Get registered resource instances.
439
* @return Set of resource instance class names
440
*/
441
Set<String> getRegisteredInstances();
442
443
/**
444
* Get registered providers.
445
* @return Set of provider class names
446
*/
447
Set<String> getProviders();
448
449
/**
450
* Get configuration properties.
451
* @return Map of configuration property names to values
452
*/
453
Map<String, Object> getProperties();
454
}
455
456
/**
457
* Resource MXBean for JMX monitoring of resource-level metrics.
458
*/
459
public interface ResourceMXBean {
460
461
/**
462
* Get resource path.
463
* @return Resource path pattern
464
*/
465
String getPath();
466
467
/**
468
* Get resource class name.
469
* @return Fully qualified resource class name
470
*/
471
String getResourceClass();
472
473
/**
474
* Get average request duration.
475
* @return Average duration in milliseconds
476
*/
477
long getAverageRequestDuration();
478
479
/**
480
* Get minimum request duration.
481
* @return Minimum duration in milliseconds
482
*/
483
long getMinRequestDuration();
484
485
/**
486
* Get maximum request duration.
487
* @return Maximum duration in milliseconds
488
*/
489
long getMaxRequestDuration();
490
491
/**
492
* Get total request count.
493
* @return Total number of requests
494
*/
495
long getRequestCount();
496
497
/**
498
* Get requests per second.
499
* @return Current requests per second rate
500
*/
501
double getRequestRate();
502
}
503
504
/**
505
* Resource method MXBean for JMX monitoring of method-level metrics.
506
*/
507
public interface ResourceMethodMXBean {
508
509
/**
510
* Get HTTP method.
511
* @return HTTP method string
512
*/
513
String getHttpMethod();
514
515
/**
516
* Get method path.
517
* @return Method path pattern
518
*/
519
String getPath();
520
521
/**
522
* Get method invocation count.
523
* @return Number of method invocations
524
*/
525
long getInvocationCount();
526
527
/**
528
* Get average execution time.
529
* @return Average execution time in milliseconds
530
*/
531
long getAverageExecutionTime();
532
533
/**
534
* Get minimum execution time.
535
* @return Minimum execution time in milliseconds
536
*/
537
long getMinExecutionTime();
538
539
/**
540
* Get maximum execution time.
541
* @return Maximum execution time in milliseconds
542
*/
543
long getMaxExecutionTime();
544
}
545
```
546
547
### Statistics Listener
548
549
Interface for receiving statistics updates and notifications.
550
551
```java { .api }
552
/**
553
* Monitoring statistics listener for receiving statistics updates.
554
*/
555
public interface MonitoringStatisticsListener {
556
557
/**
558
* Called when monitoring statistics are updated.
559
* @param event Statistics event containing updated data
560
*/
561
void onStatistics(MonitoringStatisticsEvent event);
562
563
/**
564
* Monitoring statistics event containing updated statistics data.
565
*/
566
interface MonitoringStatisticsEvent {
567
568
/**
569
* Get the updated monitoring statistics.
570
* @return Current MonitoringStatistics snapshot
571
*/
572
MonitoringStatistics getStatistics();
573
574
/**
575
* Get the event timestamp.
576
* @return When the statistics were captured
577
*/
578
Date getTimestamp();
579
}
580
}
581
```
582
583
**Usage Examples:**
584
585
```java
586
import org.glassfish.jersey.server.monitoring.*;
587
588
// Custom statistics listener
589
public class CustomStatisticsListener implements MonitoringStatisticsListener {
590
591
@Override
592
public void onStatistics(MonitoringStatisticsEvent event) {
593
MonitoringStatistics stats = event.getStatistics();
594
595
// Log overall request statistics
596
ExecutionStatistics execStats = stats.getRequestStatistics();
597
TimeWindowStatistics windowStats = execStats.getTimeWindowStatistics();
598
599
System.out.println("=== Request Statistics ===");
600
System.out.println("Total requests: " + windowStats.getRequestCount());
601
System.out.println("Requests/sec: " + windowStats.getRequestsPerSecond());
602
System.out.println("Avg duration: " + windowStats.getAverageDuration() + "ms");
603
System.out.println("Min duration: " + windowStats.getMinimumDuration() + "ms");
604
System.out.println("Max duration: " + windowStats.getMaximumDuration() + "ms");
605
606
// Log resource-specific statistics
607
Map<String, ResourceStatistics> uriStats = stats.getUriStatistics();
608
for (Map.Entry<String, ResourceStatistics> entry : uriStats.entrySet()) {
609
String uri = entry.getKey();
610
ResourceStatistics resourceStats = entry.getValue();
611
612
System.out.println("=== Resource: " + uri + " ===");
613
ExecutionStatistics resExecStats = resourceStats.getRequestExecutionStatistics();
614
TimeWindowStatistics resWindowStats = resExecStats.getTimeWindowStatistics();
615
System.out.println(" Requests: " + resWindowStats.getRequestCount());
616
System.out.println(" Avg: " + resWindowStats.getAverageDuration() + "ms");
617
618
// Method-level statistics
619
Map<String, ResourceMethodStatistics> methodStats = resourceStats.getResourceMethodStatistics();
620
for (Map.Entry<String, ResourceMethodStatistics> methodEntry : methodStats.entrySet()) {
621
ResourceMethodStatistics methodStat = methodEntry.getValue();
622
System.out.println(" " + methodStat.getMethod() + " " + methodStat.getPath() +
623
": " + methodStat.getInvocationCount() + " calls");
624
}
625
}
626
627
// Log response statistics
628
ResponseStatistics responseStats = stats.getResponseStatistics();
629
Map<Integer, Long> responseCodes = responseStats.getResponseCodes();
630
System.out.println("=== Response Codes ===");
631
for (Map.Entry<Integer, Long> entry : responseCodes.entrySet()) {
632
System.out.println(" " + entry.getKey() + ": " + entry.getValue() + " responses");
633
}
634
635
// Log exception statistics
636
Map<Class<?>, ExceptionMapperStatistics> exceptionStats = stats.getExceptionMapperStatistics();
637
if (!exceptionStats.isEmpty()) {
638
System.out.println("=== Exception Statistics ===");
639
for (Map.Entry<Class<?>, ExceptionMapperStatistics> entry : exceptionStats.entrySet()) {
640
System.out.println(" " + entry.getKey().getSimpleName() + " exceptions handled");
641
}
642
}
643
}
644
}
645
646
// Register statistics listener
647
ResourceConfig config = new ResourceConfig()
648
.packages("com.example.resources")
649
.register(CustomStatisticsListener.class);
650
```