Skip to content

Commit

Permalink
[bindings d-e] Fix exception handling (Jetty HTTP client) (openhab#10476
Browse files Browse the repository at this point in the history
)

Fixes openhab#10474

Signed-off-by: Laurent Garnier <[email protected]>
  • Loading branch information
lolodomo authored and thinkingstone committed Nov 7, 2021
1 parent ca8625f commit 53fddc2
Show file tree
Hide file tree
Showing 20 changed files with 73 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -234,8 +236,11 @@ private String executeUrl(String url) throws DaikinCommunicationException {
return response.getContentAsString();
} catch (DaikinCommunicationException e) {
throw e;
} catch (Exception e) {
} catch (ExecutionException | TimeoutException e) {
throw new DaikinCommunicationException("Daikin HTTP error", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new DaikinCommunicationException("Daikin HTTP interrupted", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
*/
@NonNullByDefault
public class BasicInfo {
private static final Logger logger = LoggerFactory.getLogger(BasicInfo.class);
private static final Logger LOGGER = LoggerFactory.getLogger(BasicInfo.class);

public String mac = "";
public String ret = "";
Expand All @@ -38,7 +38,7 @@ private BasicInfo() {
}

public static BasicInfo parse(String response) {
logger.debug("Parsing string: \"{}\"", response);
LOGGER.debug("Parsing string: \"{}\"", response);

Map<String, String> responseMap = InfoParser.parse(response);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ public class EnergyInfoDayAndWeek {
public Optional<Double> energyCoolingThisWeek = Optional.empty();
public Optional<Double> energyCoolingLastWeek = Optional.empty();

private static final Logger logger = LoggerFactory.getLogger(EnergyInfoDayAndWeek.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EnergyInfoDayAndWeek.class);

private EnergyInfoDayAndWeek() {
}

public static EnergyInfoDayAndWeek parse(String response) {
EnergyInfoDayAndWeek info = new EnergyInfoDayAndWeek();

logger.trace("Parsing string: \"{}\"", response);
LOGGER.trace("Parsing string: \"{}\"", response);

// /aircon/get_week_power_ex
// ret=OK,s_dayw=0,week_heat=1/1/1/1/1/5/2/1/1/1/1/2/1/1,week_cool=0/0/0/0/0/0/0/0/0/0/0/0/0/0
Expand Down Expand Up @@ -94,7 +94,7 @@ public static EnergyInfoDayAndWeek parse(String response) {
info.energyCoolingLastWeek = Optional.of(previousWeekEnergy / 10);
}
} else {
logger.debug("did not receive 'ret=OK' from adapter");
LOGGER.debug("did not receive 'ret=OK' from adapter");
}
return info;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ private EnergyInfoYear() {
}

public static EnergyInfoYear parse(String response) {

LOGGER.trace("Parsing string: \"{}\"", response);

Map<String, String> responseMap = InfoParser.parse(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
*/
@NonNullByDefault
public class AirbaseBasicInfo {
private static final Logger logger = LoggerFactory.getLogger(AirbaseBasicInfo.class);
private static final Logger LOGGER = LoggerFactory.getLogger(AirbaseBasicInfo.class);

public String mac = "";
public String ret = "";
Expand All @@ -39,7 +39,7 @@ private AirbaseBasicInfo() {
}

public static AirbaseBasicInfo parse(String response) {
logger.debug("Parsing string: \"{}\"", response);
LOGGER.debug("Parsing string: \"{}\"", response);

Map<String, String> responseMap = InfoParser.parse(response);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
* @author Paul Smedley - Modifications to support Airbase Controllers
* @author Lukas Agethen - Added support for Energy Year reading, compressor frequency and powerful mode
* @author Wouter Denayer - Added to support for weekly & daily energy reading
*
*
*/
@NonNullByDefault
public class DaikinAcUnitHandler extends DaikinBaseHandler {
Expand Down Expand Up @@ -281,7 +281,7 @@ maybePower.<State> map(
}

/**
*
*
* @param channel
* @param maybePower
*/
Expand All @@ -304,7 +304,7 @@ protected void registerUuid(@Nullable String key) {
return;
}
webTargets.registerUuid(key);
} catch (Exception e) {
} catch (DaikinCommunicationException e) {
// suppress exceptions
logger.debug("registerUuid({}) error: {}", key, e.getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import java.time.Duration;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -85,11 +86,14 @@ private long getMinutesFromTime(@Nullable String configTime) {
throw new NumberFormatException();
} else {
String[] splittedConfigTime = time.split(TIME_SEPARATOR);
if (splittedConfigTime.length < 2) {
throw new NumberFormatException();
}
int hour = Integer.parseInt(splittedConfigTime[0]);
int minutes = Integer.parseInt(splittedConfigTime[1]);
return Duration.ofMinutes(minutes).plusHours(hour).toMinutes();
}
} catch (Exception ex) {
} catch (PatternSyntaxException | NumberFormatException | ArithmeticException ex) {
logger.warn("Cannot parse channel configuration '{}' to hour and minutes, use pattern hh:mm, ignoring!",
time);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,13 @@ private String getResponse(String url) {
} else {
throw new DarkSkyCommunicationException(errorMessage, e.getCause());
}
} catch (InterruptedException | TimeoutException e) {
} catch (TimeoutException e) {
logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
throw new DarkSkyCommunicationException(e.getLocalizedMessage(), e.getCause());
} catch (InterruptedException e) {
logger.debug("Execution interrupted: {}", e.getLocalizedMessage(), e);
Thread.currentThread().interrupt();
throw new DarkSkyCommunicationException(e.getLocalizedMessage(), e.getCause());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ private void connectTelnetSocket() {
listener.telnetClientConnected(false);
} catch (InterruptedException e) {
logger.debug("Interrupted while connecting to {}", config.getHost(), e);
Thread.currentThread().interrupt();
}
delay = RECONNECT_DELAY;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ private void refreshState() {
Thread.sleep(300);
} catch (InterruptedException e) {
logger.trace("requestStateOverTelnet() - Interrupted while requesting state.");
Thread.currentThread().interrupt();
}
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public boolean checkConfiguration() {
* Try to auto configure the connection type (Telnet or HTTP)
* for Things not added through Paper UI.
*/
private void autoConfigure() {
private void autoConfigure() throws InterruptedException {
/*
* The isTelnet parameter has no default.
* When not set we will try to auto-detect the correct values
Expand All @@ -223,7 +223,7 @@ private void autoConfigure() {
telnetEnable = false;
httpApiUsable = true;
}
} catch (InterruptedException | TimeoutException | ExecutionException e) {
} catch (TimeoutException | ExecutionException e) {
logger.debug("Error when trying to access AVR using HTTP on port 80, reverting to Telnet mode.", e);
}

Expand All @@ -239,7 +239,7 @@ private void autoConfigure() {
httpPort = 8080;
httpApiUsable = true;
}
} catch (InterruptedException | TimeoutException | ExecutionException e) {
} catch (TimeoutException | ExecutionException e) {
logger.debug("Additionally tried to connect to port 8080, this also failed", e);
}
}
Expand All @@ -255,7 +255,7 @@ private void autoConfigure() {
response = httpClient.newRequest("http://" + host + ":" + httpPort + "/goform/Deviceinfo.xml")
.timeout(3, TimeUnit.SECONDS).send();
status = response.getStatus();
} catch (InterruptedException | TimeoutException | ExecutionException e) {
} catch (TimeoutException | ExecutionException e) {
logger.debug("Failed in fetching the Deviceinfo.xml to determine zone count", e);
}

Expand Down Expand Up @@ -303,7 +303,12 @@ public void initialize() {

// Configure Connection type (Telnet/HTTP) and number of zones
// Note: this only happens for discovered Things
autoConfigure();
try {
autoConfigure();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}

if (!checkConfiguration()) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,9 @@ protected void login(final int timeout) {
} catch (final NoSuchAlgorithmException e) {
logger.debug("login - Internal error", e);
status = HNAPStatus.INTERNAL_ERROR;
} catch (final InterruptedException e) {
status = HNAPStatus.COMMUNICATION_ERROR;
Thread.currentThread().interrupt();
} catch (final Exception e) {
// Assume there has been some problem trying to send one of the messages
if (status != HNAPStatus.COMMUNICATION_ERROR) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,9 @@ private boolean getLastDetection(final boolean isRetry) {
} else {
unexpectedResult("getLastDetection - Unexpected response", soapResponse);
}
} catch (final InterruptedException e) {
status = DeviceStatus.COMMUNICATION_ERROR;
Thread.currentThread().interrupt();
} catch (final Exception e) {
// Assume there has been some problem trying to send one of the messages
if (status != DeviceStatus.COMMUNICATION_ERROR) {
Expand Down
1 change: 1 addition & 0 deletions bundles/org.openhab.binding.ecobee/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Once logged in, select the **Developer** option from the menu.
If you don't see the **Developer** option on the menu, then something went wrong with the previous step.

4. Finally, create a new application.

Give the application a name and fill in the application summary.
Select the **Ecobee PIN** Authorization Method, then press **Create**.
You now should see the **API key** for the application you just created.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ private boolean isPinExpired() {
}
} catch (InterruptedException e) {
logger.debug("InterruptedException on call to Ecobee authorization API: {}", e.getMessage());
Thread.currentThread().interrupt();
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,13 @@ private String getResponse(String url, Map<String, String> params) {
String errorMessage = e.getLocalizedMessage();
logger.debug("Exception occurred during execution: {}", errorMessage, e);
throw new EnturCommunicationException(errorMessage, e);
} catch (InterruptedException | TimeoutException | IOException e) {
} catch (TimeoutException | IOException e) {
logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
throw new EnturCommunicationException(e.getLocalizedMessage(), e);
} catch (InterruptedException e) {
logger.debug("Execution interrupted: {}", e.getLocalizedMessage(), e);
Thread.currentThread().interrupt();
throw new EnturCommunicationException(e.getLocalizedMessage(), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,13 @@ private synchronized List<String> sendGet(String command) throws IOException {
logger.warn("Etherrain return status other than HTTP_OK : {}", response.getStatus());
return Collections.emptyList();
}
} catch (InterruptedException | TimeoutException | ExecutionException e) {
} catch (TimeoutException | ExecutionException e) {
logger.warn("Could not connect to Etherrain with exception: {}", e.getMessage());
return Collections.emptyList();
} catch (InterruptedException e) {
logger.warn("Connect to Etherrain interrupted: {}", e.getMessage());
Thread.currentThread().interrupt();
return Collections.emptyList();
}

return new BufferedReader(new StringReader(response.getContentAsString())).lines().collect(Collectors.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,11 @@ public <TOut> TOut doRequest(HttpMethod method, String url, Map<String, String>
retVal = new Gson().fromJson(reply, outClass);
}
}
} catch (InterruptedException | ExecutionException e) {
} catch (ExecutionException e) {
logger.debug("Error in handling request: ", e);
} catch (InterruptedException e) {
logger.debug("Handling request interrupted: ", e);
Thread.currentThread().interrupt();
}

return retVal;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public class EvohomeApiClient {
private static final String CLIENT_SECRET = "1a15cdb8-42de-407b-add0-059f92c530cb";

private final Logger logger = LoggerFactory.getLogger(EvohomeApiClient.class);
private final HttpClient httpClient;
private final EvohomeAccountConfiguration configuration;
private final ApiAccess apiAccess;

Expand All @@ -60,19 +59,9 @@ public class EvohomeApiClient {
* Creates a new API client based on the V2 API interface
*
* @param configuration The configuration of the account to use
* @throws Exception
*/
public EvohomeApiClient(EvohomeAccountConfiguration configuration, HttpClient httpClient) throws Exception {
public EvohomeApiClient(EvohomeAccountConfiguration configuration, HttpClient httpClient) {
this.configuration = configuration;
this.httpClient = httpClient;

try {
httpClient.start();
} catch (Exception e) {
logger.error("Could not start http client", e);
throw new EvohomeApiClientException("Could not start http client", e);
}

apiAccess = new ApiAccess(httpClient);
apiAccess.setApplicationId(APPLICATION_ID);
}
Expand All @@ -85,14 +74,6 @@ public void close() {
useraccount = null;
locations = null;
locationsStatus = null;

if (httpClient.isStarted()) {
try {
httpClient.stop();
} catch (Exception e) {
logger.debug("Could not stop http client.", e);
}
}
}

public boolean login() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,30 +74,22 @@ public void initialize() {
configuration = getConfigAs(EvohomeAccountConfiguration.class);

if (checkConfig()) {
try {
apiClient = new EvohomeApiClient(configuration, this.httpClient);
} catch (Exception e) {
logger.error("Could not start API client", e);
updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Could not create evohome API client");
}
apiClient = new EvohomeApiClient(configuration, this.httpClient);

if (apiClient != null) {
// Initialization can take a while, so kick it off on a separate thread
scheduler.schedule(() -> {
if (apiClient.login()) {
if (checkInstallationInfoHasDuplicateIds(apiClient.getInstallationInfo())) {
startRefreshTask();
} else {
updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"System Information Sanity Check failed");
}
// Initialization can take a while, so kick it off on a separate thread
scheduler.schedule(() -> {
if (apiClient.login()) {
if (checkInstallationInfoHasDuplicateIds(apiClient.getInstallationInfo())) {
startRefreshTask();
} else {
updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Authentication failed");
"System Information Sanity Check failed");
}
}, 0, TimeUnit.SECONDS);
}
} else {
updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Authentication failed");
}
}, 0, TimeUnit.SECONDS);
}
}

Expand Down

0 comments on commit 53fddc2

Please sign in to comment.