File: ListenerDefinition.java

package info (click to toggle)
libmbassador-java 1.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 788 kB
  • sloc: java: 5,488; xml: 274; sh: 12; makefile: 5
file content (169 lines) | stat: -rw-r--r-- 6,169 bytes parent folder | download | duplicates (2)
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
import net.engio.mbassy.dispatch.HandlerInvocation;
import net.engio.mbassy.listener.*;
import net.engio.mbassy.subscription.MessageEnvelope;
import net.engio.mbassy.subscription.SubscriptionContext;

import java.io.File;
import java.lang.annotation.*;

/**
 * These examples show how to configure listeners and handlers based on the available configuration options.
 *
 * NOTE: The presented handler configurations compose very well because they are implemented using decorator pattern.
 *
 */
public class ListenerDefinition {


    /**
     * By default any listener will be stored using weak references {@link java.lang.ref.WeakReference}.
     * This implies that at any give point in time, listeners might be GC'ed if no other alive object holds a reference to it.
     *
     * In managed environments where object lifecycle is controlled
     * by a framework  (Spring, Guice etc.) this is a very handy feature because no attentions needs
     * to be paid to proper unsubscription of listeners that have ended their life (session scoped beans etc.)
     *
     * NOTE: There is no dedicated maintenance task running to take care of GC'ed listeners.
     * Automatic cleanup of orphaned weak references is an embedded process done during message publication.
     *
     */
    static class WeaklyReferencedListener{
        // Handler definitions go here
    }


    /**
     * In case that there is no other mechanism managing references to the listeners and they should
     * just stick around until explicitly unsubscribed, listener classes need to be annotated accordingly.
     */
    @Listener(references = References.Strong)
    static class StronglyReferencedListener{
        // This listener will stay subscribed until explicitly unsubscribed
    }


    /**
     * This listeners demonstrates the very basic use cases of synchronous and asynchronous handler definitions.
     *
     */
    static class SyncAsyncListener{

        /**
         * Any published message will be delivered to this handler (as it consumes any object of type Object.class)
         * Delivery is done using synchronous invocation, i.e. the handler is called from the thread running the message
         * publication.
         *
         */
        @Handler
        public void synchronousHandler(Object message) {
            // do something
        }

        /**
         * According to the handler configuration, this handler is invoked asynchronously, meaning that each handler
         * invocation runs in a thread different from the one that runs the initial message publication.
         *
         * This feature is useful for computationally expensive or IO-bound tasks.
         *
         */
        @Handler(delivery = Invoke.Asynchronously)
        public void asynchronousHandler(File message) {
            // do something more expensive here
        }

    }

    static class FilteringListener{


        /**
         * This handler consumes only strings (as there are no subtypes of final String.class).
         * Furthermore, each string is passed through the list of defined filters and the handler is
         * invoked only if all filters pass. In this case, only strings starting with 'http' will be handled.
         *
         */
        @Handler(delivery = Invoke.Synchronously,
                filters = {@Filter(Urlfilter.class)})
        public void httpUrlsOnly(String message) {

        }

        /**
         * Another way of controlling which messages are delivered to handlers is by using JUEL expressions.
         * These can be specified as conditions (no type checking etc.) and will be evaluated on the msg.
         * This particular condition will filter out all empty strings
         */
        @Handler(condition = "!msg.isEmpty()")
        public void handleNonEmptyStrings(String msg) {
        }

        /**
         *
         */
        @Handler(delivery = Invoke.Synchronously, rejectSubtypes = true)
        @Enveloped(messages = {Object.class, String.class})
        public void handleUnrelatedMessageTypes(MessageEnvelope envelope) {
            // the envelope will contain either an instance of Object.class or String.class
            // if rejectSubtypes were set to 'false' (default) also subtypes of TestMessage or TestMessage2 would be allowed
        }

        static class Urlfilter implements IMessageFilter<String>{
            public boolean accepts(String message, SubscriptionContext context){
                return message.startsWith("http");
            }
        }

    }



    /**
     *  Listeners can use custom code to invoke their handlers. Custom invocation logic is defined on a per-handler
     *  basis (as the signature requires knowledge about concrete handler and message type).
     */
    @Listener(references = References.Strong)
    static class CustomInvocationListener {

        @Handler(invocation = TimingInvocation.class)
        public void handle(File message) {
            // do timed operation here
        }

        public static class TimingInvocation extends HandlerInvocation<CustomInvocationListener, File> {

            public TimingInvocation(SubscriptionContext context) {
                super(context);
            }

            @Override
            public void invoke(CustomInvocationListener listener, File message) {
                long start = System.currentTimeMillis();
                listener.handle(message);
                long duration = System.currentTimeMillis() - start;
                System.out.println("Time takes for handler invocation: " + duration + " ms");
            }
        }

    }


    /**
     * Handler annotation that adds a condition checking for positive integers only
     */
    @Retention(value = RetentionPolicy.RUNTIME)
    @Inherited
    @Handler(condition = "msg.getClass() == Integer.class && msg > 0")
    @Synchronized
    @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE })
    @interface SynchronizedPositiveIntegers{}

    static class ListenerWithCustomAnnotation{

        @SynchronizedPositiveIntegers
        public void handlePositiveIntegers(Integer msg){

        }

    }

}