3333import org .eclipse .jetty .http .HttpStatus ;
3434import org .eclipse .jetty .http .MimeTypes ;
3535import org .openhab .binding .huesync .internal .HueSyncConstants .ENDPOINTS ;
36+ import org .openhab .binding .huesync .internal .config .HueSyncConfiguration ;
3637import org .openhab .binding .huesync .internal .exceptions .HueSyncConnectionException ;
3738import org .openhab .core .io .net .http .TlsTrustManagerProvider ;
3839import org .osgi .framework .BundleContext ;
4849/**
4950 *
5051 * @author Patrik Gfeller - Initial Contribution
52+ * @author Patrik Gfeller - Issue #18376, Fix/improve log message and exception handling
5153 */
5254@ NonNullByDefault
5355public class HueSyncConnection {
5456 public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper ()
5557 .configure (DeserializationFeature .FAIL_ON_UNKNOWN_PROPERTIES , false );
5658 /**
5759 * Request format: The Sync Box API can be accessed locally via HTTPS on root
58- * level (port 443,
59- * /api/v1), resource level /api/v1/<resource> and in some cases sub-resource
60- * level
61- * /api/v1/<resource>/<sub-resource>.
60+ * level (port 443, /api/v1), resource level /api/v1/<resource>
61+ * and in some cases sub-resource level /api/v1/<resource>/<sub-resource>.
6262 */
6363 private static final String REQUEST_FORMAT = "https://%s:%s/%s/%s" ;
6464 private static final String API = "api/v1" ;
@@ -110,10 +110,10 @@ protected ContentResponse execute() throws InterruptedException, ExecutionExcept
110110
111111 protected String registrationId = "" ;
112112
113- public HueSyncConnection (HttpClient httpClient , String host , Integer port )
113+ public HueSyncConnection (HttpClient httpClient , HueSyncConfiguration configuration )
114114 throws CertificateException , IOException , URISyntaxException {
115- this .host = host ;
116- this .port = port ;
115+ this .host = configuration . host ;
116+ this .port = configuration . port ;
117117
118118 this .deviceUri = new URI (String .format ("https://%s:%s" , this .host , this .port ));
119119
@@ -123,9 +123,10 @@ public HueSyncConnection(HttpClient httpClient, String host, Integer port)
123123 this .tlsProviderService = context .registerService (TlsTrustManagerProvider .class .getName (), trustManagerProvider ,
124124 null );
125125 this .httpClient = httpClient ;
126+ this .updateAuthentication (configuration .registrationId , configuration .apiAccessToken );
126127 }
127128
128- public void updateAuthentication (String id , String token ) {
129+ public final void updateAuthentication (String id , String token ) {
129130 this .removeAuthentication ();
130131
131132 if (!id .isBlank () && !token .isBlank ()) {
@@ -139,7 +140,6 @@ public void updateAuthentication(String id, String token) {
139140 // #region protected
140141 protected @ Nullable <T > T executeRequest (HttpMethod method , String endpoint , String payload ,
141142 @ Nullable Class <T > type ) throws HueSyncConnectionException {
142-
143143 return this .executeRequest (new Request (method , endpoint , payload ), type );
144144 }
145145
@@ -173,43 +173,63 @@ protected void dispose() {
173173 // #region private
174174
175175 private @ Nullable <T > T executeRequest (Request request , @ Nullable Class <T > type ) throws HueSyncConnectionException {
176- String message = "@text/connection.generic-error" ;
176+ var message = "@text/connection.generic-error" ;
177177
178178 try {
179- ContentResponse response = request .execute ();
179+ var response = request .execute ();
180180
181181 /*
182182 * 400 Invalid State: Registration in progress
183183 *
184184 * 401 Authentication failed: If credentials are missing or invalid, errors out.
185- * If
186- * credentials are missing, continues on to GET only the Configuration state
187- * when
188- * unauthenticated, to allow for device identification.
185+ * If credentials are missing, continues on to GET only the Configuration
186+ * state when unauthenticated, to allow for device identification.
189187 *
190188 * 404 Invalid URI Path: Accessing URI path which is not supported
191189 *
192190 * 500 Internal: Internal errors like out of memory
193191 */
194192 switch (response .getStatus ()) {
195- case HttpStatus .OK_200 -> {
193+ case HttpStatus .OK_200 :
196194 return this .deserialize (response .getContentAsString (), type );
197- }
198- case HttpStatus .BAD_REQUEST_400 -> {
199- logger .debug ("registration in progress: no token received yet" );
200- return null ;
201- }
202- case HttpStatus .UNAUTHORIZED_401 -> message = "@text/connection.invalid-login" ;
203- case HttpStatus .NOT_FOUND_404 -> message = "@text/connection.generic-error" ;
204195 }
205- throw new HueSyncConnectionException (message , new HttpResponseException (message , response ));
206- } catch (JsonProcessingException | InterruptedException | ExecutionException | TimeoutException e ) {
207196
208- var logMessage = message + " {}" ;
209- this .logger .warn (logMessage , e .toString ());
197+ handleResponseStatus (response .getStatus (), new HttpResponseException (response .getReason (), response ));
198+ } catch (ExecutionException e ) {
199+ this .logger .trace ("{}: {}" , e .getMessage (), message );
200+
201+ if (e .getCause () instanceof HttpResponseException httpResponseException ) {
202+ handleResponseStatus (httpResponseException .getResponse ().getStatus (), httpResponseException );
203+ }
204+
205+ throw new HueSyncConnectionException (message , e );
206+ } catch (HttpResponseException e ) {
207+ handleResponseStatus (e .getResponse ().getStatus (), e );
208+ } catch (JsonProcessingException | InterruptedException | TimeoutException e ) {
209+ this .logger .trace ("{}: {}" , e .getMessage (), message );
210210
211211 throw new HueSyncConnectionException (message , e );
212212 }
213+
214+ throw new HueSyncConnectionException (message );
215+ }
216+
217+ private void handleResponseStatus (int status , Exception e ) throws HueSyncConnectionException {
218+ var message = "@text/connection.generic-error" ;
219+
220+ switch (status ) {
221+ case HttpStatus .BAD_REQUEST_400 :
222+ case HttpStatus .UNAUTHORIZED_401 :
223+ message = "@text/connection.invalid-login" ;
224+ break ;
225+ case HttpStatus .NOT_FOUND_404 :
226+ message = "@text/connection.generic-error" ;
227+ break ;
228+ }
229+
230+ this .logger .trace ("Status: {}, Message Key: {}" , status , message );
231+
232+ throw new HueSyncConnectionException (message , e );
213233 }
214234
215235 private @ Nullable <T > T deserialize (String json , @ Nullable Class <T > type ) throws JsonProcessingException {
0 commit comments