1717
1818package  org .softwarefactory .keycloak .providers .events .mqtt ;
1919
20- import  org .keycloak .events .Event ;
21- import  org .keycloak .events .EventListenerProvider ;
22- import  org .keycloak .events .EventType ;
23- import  org .keycloak .events .admin .AdminEvent ;
24- import  org .keycloak .events .admin .OperationType ;
20+ import  java .util .Map ;
21+ import  java .util .logging .Level ;
22+ import  java .util .logging .Logger ;
2523
2624import  org .eclipse .paho .client .mqttv3 .IMqttClient ;
27- import  org .eclipse .paho .client .mqttv3 .MqttMessage ;
2825import  org .eclipse .paho .client .mqttv3 .MqttClient ;
2926import  org .eclipse .paho .client .mqttv3 .MqttConnectOptions ;
27+ import  org .eclipse .paho .client .mqttv3 .MqttMessage ;
3028import  org .eclipse .paho .client .mqttv3 .persist .MemoryPersistence ;
31- 
3229import  org .json .simple .JSONObject ;
33- 
34- import  java . util . Map ;
35- import  java . util . Set ;
36- import  java . lang . Exception ;
30+ import   org . keycloak . events . Event ; 
31+ import  org . keycloak . events . EventListenerProvider ;
32+ import  org . keycloak . events . admin . AdminEvent ;
33+ import  org . softwarefactory . keycloak . providers . events . models . Configuration ;
3734
3835/** 
3936 * @author <a href="mailto:[email protected] ">Matthieu Huin</a> 4037 */ 
4138public  class  MQTTEventListenerProvider  implements  EventListenerProvider  {
39+     private  static  final  Logger  logger  = Logger .getLogger (MQTTEventListenerProvider .class .getName ());
40+ 
41+     private  Configuration  configuration ;
42+     public  static  final  String  PUBLISHER_ID  = "keycloak" ;
4243
43-     private  Set <EventType > excludedEvents ;
44-     private  Set <OperationType > excludedAdminOperations ;
45-     private  String  serverUri ;
46-     private  String  username ;
47-     private  String  password ;
48-     public  static  final  String  publisherId  = "keycloak" ;
49-     public  String  TOPIC ;
50-     public  boolean  usePersistence ;
51- 
52-     public  MQTTEventListenerProvider (Set <EventType > excludedEvents , Set <OperationType > excludedAdminOperations , String  serverUri , String  username , String  password , String  topic , boolean  usePersistence ) {
53-         this .excludedEvents  = excludedEvents ;
54-         this .excludedAdminOperations  = excludedAdminOperations ;
55-         this .serverUri  = serverUri ;
56-         this .username  = username ;
57-         this .password  = password ;
58-         this .TOPIC  = topic ;
59-         this .usePersistence  = usePersistence ;
44+     public  MQTTEventListenerProvider (Configuration  configuration ) {
45+         this .configuration  = configuration ;
6046    }
6147
6248    @ Override 
6349    public  void  onEvent (Event  event ) {
6450        // Ignore excluded events 
65-         if  (excludedEvents  != null  && excludedEvents .contains (event .getType ())) {
66-             return ;
67-         } else  {
68-             String  stringEvent  = toString (event );
69-             try  {
70-                 MemoryPersistence  persistence  = null ;
71-                 if  (this .usePersistence  == true ) {
72-                     persistence  = new  MemoryPersistence ();
73-                 }
74-                 MqttClient  client  = new  MqttClient (this .serverUri  ,publisherId , persistence );
75-                 MqttConnectOptions  options  = new  MqttConnectOptions ();
76-                 options .setAutomaticReconnect (true );
77-                 options .setCleanSession (true );
78-                 options .setConnectionTimeout (10 );
79-                 if  (this .username  != null  && this .password  != null ) {
80-                     options .setUserName (this .username );
81-                     options .setPassword (this .password .toCharArray ());
82-                 }
83-                 client .connect (options );
84-                 System .out .println ("EVENT: "  + stringEvent );
85-                 MqttMessage  payload  = toPayload (stringEvent );
86-                 payload .setQos (0 );
87-                 payload .setRetained (true );
88-                 client .publish (this .TOPIC , payload );
89-                 client .disconnect ();
90-             } catch (Exception  e ) {
91-                 // ? 
92-                 System .out .println ("Caught the following error: "  + e .toString ());
93-                 e .printStackTrace ();
94-                 return ;
95-             }
51+         if  (configuration .excludedEvents  == null  || !configuration .excludedEvents .contains (event .getType ())) {
52+             sendMqttMessage (convertEvent (event ));
9653        }
9754    }
9855
9956    @ Override 
10057    public  void  onEvent (AdminEvent  event , boolean  includeRepresentation ) {
10158        // Ignore excluded operations 
102-         if  (excludedAdminOperations  != null  && excludedAdminOperations .contains (event .getOperationType ())) {
103-             return ;
104-         } else  {
105-             String  stringEvent  = toString (event );
106-             try  {
107-                 MemoryPersistence  persistence  = null ;
108-                 if  (this .usePersistence  == true ) {
109-                     persistence  = new  MemoryPersistence ();
110-                 }
111-                 MqttClient  client  = new  MqttClient (this .serverUri  ,publisherId , persistence );
112-                 MqttConnectOptions  options  = new  MqttConnectOptions ();
113-                 options .setAutomaticReconnect (true );
114-                 options .setCleanSession (true );
115-                 options .setConnectionTimeout (10 );
116-                 if  (this .username  != null  && this .password  != null ) {
117-                     options .setUserName (this .username );
118-                     options .setPassword (this .password .toCharArray ());
119-                 }
120-                 client .connect (options );
121-                 // System.out.println("EVENT: " + stringEvent); 
122-                 MqttMessage  payload  = toPayload (stringEvent );
123-                 payload .setQos (0 );
124-                 payload .setRetained (true );
125-                 client .publish (this .TOPIC , payload );
126-                 client .disconnect ();
127-             } catch (Exception  e ) {
128-                 // ? 
129-                 System .out .println ("Caught the following error: "  + e .toString ());
130-                 e .printStackTrace ();
131-                 return ;
132-             }
59+         if  (configuration .excludedAdminOperations  == null 
60+                 || !configuration .excludedAdminOperations .contains (event .getOperationType ())) {
61+             sendMqttMessage (convertAdminEvent (event ));
13362        }
13463    }
13564
65+     private  void  sendMqttMessage (String  event ) {
66+         MemoryPersistence  persistence  = null ;
67+         if  (configuration .usePersistence ) {
68+             persistence  = new  MemoryPersistence ();
69+         }
70+ 
71+         try  (IMqttClient  client  = new  MqttClient (configuration .serverUri , PUBLISHER_ID , persistence )) {
72+             MqttConnectOptions  options  = new  MqttConnectOptions ();
73+             options .setAutomaticReconnect (true );
74+             options .setCleanSession (configuration .cleanSession );
75+             options .setConnectionTimeout (10 );
13676
77+             if  (configuration .username  != null  && configuration .password  != null ) {
78+                 options .setUserName (configuration .username );
79+                 options .setPassword (configuration .password .toCharArray ());
80+             }
81+ 
82+             client .connect (options );
83+             logger .log (Level .FINE , "Event: {0}" , event );
84+             MqttMessage  payload  = toPayload (event );
85+             payload .setQos (configuration .qos );
86+             payload .setRetained (configuration .retained );
87+             client .publish (configuration .topic , payload );
88+             client .disconnect ();
89+         } catch  (Exception  e ) {
90+             logger .log (Level .SEVERE , "Event: {0}" , e .getStackTrace ());
91+         }
92+     }
13793
13894    private  MqttMessage  toPayload (String  s ) {
13995        byte [] payload  = s .getBytes ();
14096        return  new  MqttMessage (payload );
14197    }
14298
143-     private  String  toString (Event  event ) {
144-         JSONObject  obj  = toJSON (event );
145-         return  obj .toString ();
146- 
147-     }
148- 
149-     private  JSONObject  toJSON (Event  event ) {
99+     private  String  convertEvent (Event  event ) {
150100        JSONObject  ev  = new  JSONObject ();
151101
152102        ev .put ("type" , event .getType ().toString ());
@@ -157,7 +107,7 @@ private JSONObject toJSON(Event event) {
157107        ev .put ("time" , event .getTime ());
158108
159109        ev .put ("error" , event .getError ());
160-          
110+ 
161111        JSONObject  evDetails  = new  JSONObject ();
162112        if  (event .getDetails () != null ) {
163113            for  (Map .Entry <String , String > e  : event .getDetails ().entrySet ()) {
@@ -166,19 +116,13 @@ private JSONObject toJSON(Event event) {
166116        }
167117        ev .put ("details" , evDetails );
168118
169-         return  ev ;
170-     }
171- 
172-     private  String  toString (AdminEvent  adminEvent ) {
173-         JSONObject  obj  = toJSON (adminEvent );
174-         return  obj .toString ();
175- 
119+         return  ev .toString ();
176120    }
177121
178-     private  JSONObject   toJSON (AdminEvent  adminEvent ) {
122+     private  String   convertAdminEvent (AdminEvent  adminEvent ) {
179123        JSONObject  ev  = new  JSONObject ();
180124
181-         ev .put ("type" ,adminEvent .getOperationType ().toString ());
125+         ev .put ("type" ,  adminEvent .getOperationType ().toString ());
182126        ev .put ("realmId" , adminEvent .getAuthDetails ().getRealmId ());
183127        ev .put ("clientId" , adminEvent .getAuthDetails ().getClientId ());
184128        ev .put ("userId" , adminEvent .getAuthDetails ().getUserId ());
@@ -189,11 +133,11 @@ private JSONObject toJSON(AdminEvent adminEvent) {
189133
190134        ev .put ("error" , adminEvent .getError ());
191135
192-         return  ev ;
136+         return  ev . toString () ;
193137    }
194138
195139    @ Override 
196140    public  void  close () {
197141    }
198142
199- }
143+ }
0 commit comments