55
66import  info .unterrainer .oauthtokenmanager .OauthTokenManager ;
77import  io .javalin .Javalin ;
8+ import  io .javalin .websocket .WsExceptionHandler ;
89import  io .javalin .websocket .WsHandler ;
910import  lombok .extern .slf4j .Slf4j ;
1011
@@ -19,27 +20,47 @@ public class WebsocketServer {
1920	private  boolean  isOauthEnabled  = false ;
2021
2122	public  WebsocketServer () {
22- 		wss  =  Javalin . create ( );
23+ 		this ( null );
2324	}
2425
25- 	public  WebsocketServer (String  keycloakHost , String  keycloakRealm ) {
26- 		this .keycloakHost  = keycloakHost ;
27- 		this .realm  = keycloakRealm ;
28- 
26+ 	public  WebsocketServer (WsExceptionHandler <Exception > exceptionHandler ) {
2927		try  {
30- 			tokenManager  = new  OauthTokenManager (this .keycloakHost , this .realm );
31- 			tokenManager .initPublicKey ();
3228			wss  = Javalin .create ();
3329			wss .exception (Exception .class , (e , ctx ) -> {
3430				log .error ("Uncaught exception in Websocket-Server: {}" , e );
3531			});
32+ 			if  (exceptionHandler  != null )
33+ 				wss .wsException (Exception .class , exceptionHandler );
3634			wss .wsException (Exception .class , (e , ctx ) -> {
3735				log .error ("Uncaught websocket-exception in Websocket-Server: {}" , e );
3836			});
37+ 		} catch  (Exception  e ) {
38+ 			log .error ("Error initializing Websocket-Server." , e );
39+ 		}
40+ 	}
41+ 
42+ 	public  WebsocketServer (String  keycloakHost , String  keycloakRealm ) {
43+ 		this (keycloakHost , keycloakRealm , null );
44+ 	}
45+ 
46+ 	public  WebsocketServer (String  keycloakHost , String  keycloakRealm , WsExceptionHandler <Exception > exceptionHandler ) {
47+ 		this (exceptionHandler );
48+ 		if  (keycloakHost  == null  || keycloakHost .isEmpty ()) {
49+ 			throw  new  IllegalArgumentException ("Keycloak host must not be null or empty." );
50+ 		}
51+ 		if  (keycloakRealm  == null  || keycloakRealm .isEmpty ()) {
52+ 			throw  new  IllegalArgumentException ("Keycloak realm must not be null or empty." );
53+ 		}
54+ 		this .keycloakHost  = keycloakHost ;
55+ 		this .realm  = keycloakRealm ;
56+ 
57+ 		try  {
58+ 			tokenManager  = new  OauthTokenManager (this .keycloakHost , this .realm );
59+ 			tokenManager .initPublicKey ();
3960			isOauthEnabled  = true ;
4061		} catch  (Exception  e ) {
41- 			// Exceptions will terminate a request later on, but should not terminate the 
42- 			// main-thread here. 
62+ 			log . error ( "Error initializing OauthTokenManager." ,  e ); 
63+ 			return ; 
4364		}
4465	}
4566
0 commit comments