Skip to content

Commit 91024be

Browse files
authored
[huesync] Fix resolving language resource string for an Exception (openhab#18508)
Basic manual test with openHAB 5.0.0 - Build openhab#4616 Signed-off-by: Patrik Gfeller <patrik.gfeller@proton.me>
1 parent 8a1593f commit 91024be

File tree

9 files changed

+302
-212
lines changed

9 files changed

+302
-212
lines changed

bundles/org.openhab.binding.huesync/src/main/java/org/openhab/binding/huesync/internal/HueSyncConstants.java

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,6 @@
2323
*/
2424
@NonNullByDefault
2525
public class HueSyncConstants {
26-
public static class EXCEPTION_TYPES {
27-
public static class CONNECTION {
28-
public static final String UNAUTHORIZED_401 = "invalidLogin";
29-
public static final String NOT_FOUND_404 = "notFound";
30-
public static final String INTERNAL_SERVER_ERROR_500 = "deviceError";
31-
}
32-
}
3326

3427
public static class ENDPOINTS {
3528
public static final String DEVICE = "device";
@@ -89,11 +82,6 @@ public static class HDMI {
8982
public static final String PARAMETER_HOST = "host";
9083
public static final String PARAMETER_PORT = "port";
9184

92-
public static final Integer REGISTRATION_INITIAL_DELAY = 5;
93-
public static final Integer REGISTRATION_INTERVAL = 1;
94-
95-
public static final Integer POLL_INITIAL_DELAY = 10;
96-
9785
public static final String REGISTRATION_ID = "registrationId";
9886
public static final String API_TOKEN = "apiAccessToken";
9987
}

bundles/org.openhab.binding.huesync/src/main/java/org/openhab/binding/huesync/internal/connection/HueSyncConnection.java

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import org.eclipse.jetty.http.HttpStatus;
3434
import org.eclipse.jetty.http.MimeTypes;
3535
import org.openhab.binding.huesync.internal.HueSyncConstants.ENDPOINTS;
36+
import org.openhab.binding.huesync.internal.config.HueSyncConfiguration;
3637
import org.openhab.binding.huesync.internal.exceptions.HueSyncConnectionException;
3738
import org.openhab.core.io.net.http.TlsTrustManagerProvider;
3839
import org.osgi.framework.BundleContext;
@@ -48,17 +49,16 @@
4849
/**
4950
*
5051
* @author Patrik Gfeller - Initial Contribution
52+
* @author Patrik Gfeller - Issue #18376, Fix/improve log message and exception handling
5153
*/
5254
@NonNullByDefault
5355
public 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 {

bundles/org.openhab.binding.huesync/src/main/java/org/openhab/binding/huesync/internal/connection/HueSyncDeviceConnection.java

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
* Handles the connection to a Hue HDMI Sync Box using the official API.
5151
*
5252
* @author Patrik Gfeller - Initial Contribution
53+
* @author Patrik Gfeller - Issue #18376, Fix/improve log message and exception handling
5354
*/
5455
@NonNullByDefault
5556
public class HueSyncDeviceConnection {
@@ -62,11 +63,15 @@ public class HueSyncDeviceConnection {
6263

6364
public HueSyncDeviceConnection(HttpClient httpClient, HueSyncConfiguration configuration,
6465
HueSyncExceptionHandler exceptionHandler) throws CertificateException, IOException, URISyntaxException {
65-
6666
this.exceptionHandler = exceptionHandler;
67-
this.connection = new HueSyncConnection(httpClient, configuration.host, configuration.port);
67+
try {
68+
this.connection = new HueSyncConnection(httpClient, configuration);
6869

69-
registerCommandHandlers();
70+
registerCommandHandlers();
71+
} catch (IOException | URISyntaxException | CertificateException e) {
72+
exceptionHandler.handle(e);
73+
throw e;
74+
}
7075
}
7176

7277
// #region private
@@ -200,9 +205,9 @@ public void dispose() {
200205
this.connection.dispose();
201206
}
202207

203-
public void updateConfiguration(HueSyncConfiguration config) {
204-
this.logger.debug("Connection configuration update for device {}:{} - Registration Id [{}]", config.host,
205-
config.port, config.registrationId);
208+
public void updateAuthentication(HueSyncConfiguration config) {
209+
this.logger.debug("Configure authentication for device {}:{} - Registration Id [{}]", config.host, config.port,
210+
config.registrationId);
206211

207212
this.connection.updateAuthentication(config.registrationId, config.apiAccessToken);
208213
}

bundles/org.openhab.binding.huesync/src/main/java/org/openhab/binding/huesync/internal/exceptions/HueSyncConnectionException.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,15 @@
1212
*/
1313
package org.openhab.binding.huesync.internal.exceptions;
1414

15+
import java.util.Optional;
16+
1517
import org.eclipse.jdt.annotation.NonNullByDefault;
1618
import org.eclipse.jdt.annotation.Nullable;
1719

1820
/**
1921
*
2022
* @author Patrik Gfeller - Initial contribution
23+
* @author Patrik Gfeller - Issue #18376, Fix/improve log message and exception handling
2124
*/
2225
@NonNullByDefault
2326
public class HueSyncConnectionException extends HueSyncException {
@@ -36,4 +39,16 @@ public HueSyncConnectionException(String message) {
3639
public @Nullable Exception getInnerException() {
3740
return this.innerException;
3841
}
42+
43+
@Override
44+
public @Nullable String getLocalizedMessage() {
45+
var innerMessage = Optional.ofNullable(this.innerException.getLocalizedMessage());
46+
var message = super.getLocalizedMessage();
47+
48+
if (innerMessage.isPresent()) {
49+
message = message + " (" + innerMessage.get() + ")";
50+
}
51+
52+
return message;
53+
}
3954
}

0 commit comments

Comments
 (0)