From 167f8ebc496afbfe4697492f13c2c31efaf80cd3 Mon Sep 17 00:00:00 2001 From: Christoph Weitkamp Date: Mon, 3 Jan 2022 16:05:08 +0100 Subject: [PATCH] Avoid UnsupportedEncodingException & use const from StandardCharsets (#11948) Signed-off-by: Christoph Weitkamp --- .../internal/AccountServlet.java | 12 +--- .../internal/BigAssFanBindingConstants.java | 3 - .../internal/discovery/DiscoveryListener.java | 8 +-- .../internal/handler/BigAssFanHandler.java | 10 +--- .../http/DenonMarantzHttpConnector.java | 24 +++----- .../internal/handler/IT100BridgeHandler.java | 3 +- .../ecobee/internal/api/EcobeeApi.java | 5 +- .../internal/api/EvohomeApiClient.java | 16 ++--- .../foobot/internal/FoobotApiConnector.java | 9 ++- .../internal/api/FreeboxApiManager.java | 7 +-- .../internal/handler/GlobalCacheHandler.java | 32 +++------- .../groheondus/internal/AccountServlet.java | 11 +--- .../HaasSohnpelletstoveJSONCommunication.java | 13 ++-- .../hccrubbishcollection/internal/API.java | 23 +++----- .../heos/internal/json/HeosJsonParser.java | 7 +-- .../heos/internal/resources/HeosCommands.java | 11 +--- .../internal/common/HomematicConfig.java | 12 ++-- .../communicator/message/BinRpcMessage.java | 20 +++---- .../communicator/message/XmlRpcResponse.java | 5 +- .../ihc/internal/ws/IhcClientTest.java | 8 +-- .../binding/ipcamera/internal/Helper.java | 9 +-- .../internal/onvif/OnvifConnection.java | 4 +- .../internal/protocol/KodiConnection.java | 16 ++--- .../ThirdGenerationHandler.java | 6 +- .../internal/security/LxWsSecurityToken.java | 17 +----- .../internal/MagentaTVBindingConstants.java | 3 - .../internal/handler/MagentaTVControl.java | 6 +- .../network/MagentaTVNotifyServlet.java | 3 +- .../internal/network/MagentaTVOAuth.java | 8 +-- .../mihome/internal/EncryptionHelper.java | 10 +--- .../binding/miio/internal/MiIoCrypto.java | 8 +-- .../internal/handler/MyQAccountHandler.java | 11 ++-- .../nest/internal/sdm/dto/SDMDataUtil.java | 6 +- .../connector/UplinkWebInterface.java | 3 - .../internal/state/PowermaxPanelSettings.java | 8 +-- .../RadioThermostatDiscoveryService.java | 8 +-- .../internal/model/cmd/NameCommand.java | 13 +--- .../shelly/internal/util/ShellyUtils.java | 7 +-- .../siemensrds/internal/RdsDataPoints.java | 4 +- .../internal/connector/WebInterface.java | 3 - .../handler/SomfyTahomaBridgeHandler.java | 7 +-- .../handler/SqueezeBoxServerHandler.java | 18 +----- .../internal/TouchWandRestClient.java | 16 ++--- .../internal/handler/UpnpRendererHandler.java | 59 +++++++------------ .../VenstarThermostatDiscoveryService.java | 7 +-- .../zoneminder/internal/handler/ZmAuth.java | 11 +--- .../internal/handler/DeviceActionHandler.java | 20 +++---- .../handler/DeviceHistoryHandler.java | 10 ++-- .../openhab/io/neeo/internal/NeeoUtil.java | 26 +------- .../JavaScriptTransformationService.java | 11 ++-- .../internal/cloudapi/VoiceRSSCloudImpl.java | 11 +--- .../nest/internal/wwn/dto/WWNDataUtil.java | 6 +- 52 files changed, 180 insertions(+), 414 deletions(-) diff --git a/bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/AccountServlet.java b/bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/AccountServlet.java index 6ebc28406..cc524e2cb 100644 --- a/bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/AccountServlet.java +++ b/bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/AccountServlet.java @@ -15,7 +15,6 @@ package org.openhab.binding.amazonechocontrol.internal; import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; @@ -88,11 +87,11 @@ public class AccountServlet extends HttpServlet { this.gson = gson; try { - servletUrlWithoutRoot = "amazonechocontrol/" + URLEncoder.encode(id, "UTF8"); + servletUrlWithoutRoot = "amazonechocontrol/" + URLEncoder.encode(id, StandardCharsets.UTF_8); servletUrl = "/" + servletUrlWithoutRoot; httpService.registerServlet(servletUrl, this, null, httpService.createDefaultHttpContext()); - } catch (UnsupportedEncodingException | NamespaceException | ServletException e) { + } catch (NamespaceException | ServletException e) { throw new IllegalStateException(e.getMessage()); } } @@ -340,12 +339,7 @@ public class AccountServlet extends HttpServlet { String[] elements = param.split("="); if (elements.length == 2) { String name = elements[0]; - String value = ""; - try { - value = URLDecoder.decode(elements[1], "UTF8"); - } catch (UnsupportedEncodingException e) { - logger.info("Unsupported encoding", e); - } + String value = URLDecoder.decode(elements[1], StandardCharsets.UTF_8); map.put(name, value); } } diff --git a/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/BigAssFanBindingConstants.java b/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/BigAssFanBindingConstants.java index 7e935c241..c032e6197 100644 --- a/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/BigAssFanBindingConstants.java +++ b/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/BigAssFanBindingConstants.java @@ -34,9 +34,6 @@ public class BigAssFanBindingConstants { // Fans communicate on this port using both UDP (discovery) and TCP (commands) public static final int BAF_PORT = 31415; - // Commands sent to/from fan are ASCII - public static final String CHARSET = "US-ASCII"; - // BigAssFan Thing Type UIDs public static final ThingTypeUID THING_TYPE_FAN = new ThingTypeUID(BINDING_ID, "fan"); public static final ThingTypeUID THING_TYPE_LIGHT = new ThingTypeUID(BINDING_ID, "light"); diff --git a/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/discovery/DiscoveryListener.java b/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/discovery/DiscoveryListener.java index 06fe45508..842eb47b8 100644 --- a/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/discovery/DiscoveryListener.java +++ b/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/discovery/DiscoveryListener.java @@ -12,16 +12,16 @@ */ package org.openhab.binding.bigassfan.internal.discovery; -import static org.openhab.binding.bigassfan.internal.BigAssFanBindingConstants.*; +import static org.openhab.binding.bigassfan.internal.BigAssFanBindingConstants.BAF_PORT; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,12 +60,10 @@ public class DiscoveryListener { rcvBuffer = new byte[256]; rcvPacket = new DatagramPacket(rcvBuffer, rcvBuffer.length); bcastAddress = InetAddress.getByName(BCAST_ADDRESS); - bcastBuffer = POLL_MESSAGE.getBytes(CHARSET); + bcastBuffer = POLL_MESSAGE.getBytes(StandardCharsets.US_ASCII); bcastPacket = new DatagramPacket(bcastBuffer, bcastBuffer.length, bcastAddress, BAF_PORT); } catch (UnknownHostException uhe) { logger.warn("UnknownHostException sending poll request for fans: {}", uhe.getMessage(), uhe); - } catch (UnsupportedEncodingException e) { - logger.warn("Unable to convert buffer to string using {} charset", CHARSET, e); } } diff --git a/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/handler/BigAssFanHandler.java b/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/handler/BigAssFanHandler.java index eacc428f2..d3dd4b353 100644 --- a/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/handler/BigAssFanHandler.java +++ b/bundles/org.openhab.binding.bigassfan/src/main/java/org/openhab/binding/bigassfan/internal/handler/BigAssFanHandler.java @@ -16,7 +16,6 @@ import static org.openhab.binding.bigassfan.internal.BigAssFanBindingConstants.* import java.io.DataOutputStream; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; @@ -24,6 +23,7 @@ import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.BufferOverflowException; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -611,13 +611,7 @@ public class BigAssFanHandler extends BaseThingHandler { } logger.debug("Sending message to {} at {}: {}", thing.getUID(), ipAddress, command); - byte[] buffer; - try { - buffer = command.getBytes(CHARSET); - } catch (UnsupportedEncodingException e) { - logger.warn("Unable to convert to string using {} charset: {}", CHARSET, e.getMessage(), e); - return; - } + byte[] buffer = command.getBytes(StandardCharsets.US_ASCII); try { conn.write(buffer); } catch (IOException e) { diff --git a/bundles/org.openhab.binding.denonmarantz/src/main/java/org/openhab/binding/denonmarantz/internal/connector/http/DenonMarantzHttpConnector.java b/bundles/org.openhab.binding.denonmarantz/src/main/java/org/openhab/binding/denonmarantz/internal/connector/http/DenonMarantzHttpConnector.java index 57a4593a7..d0a349efd 100644 --- a/bundles/org.openhab.binding.denonmarantz/src/main/java/org/openhab/binding/denonmarantz/internal/connector/http/DenonMarantzHttpConnector.java +++ b/bundles/org.openhab.binding.denonmarantz/src/main/java/org/openhab/binding/denonmarantz/internal/connector/http/DenonMarantzHttpConnector.java @@ -16,7 +16,6 @@ import java.beans.Introspector; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -172,22 +171,17 @@ public class DenonMarantzHttpConnector extends DenonMarantzConnector { return; } - try { - String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName()); - logger.trace("Calling url {}", url); + String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset()); + logger.trace("Calling url {}", url); - httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() { - @Override - public void onComplete(Result result) { - if (result.getResponse().getStatus() != 200) { - logger.warn("Error {} while sending command", result.getResponse().getReason()); - } + httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() { + @Override + public void onComplete(Result result) { + if (result.getResponse().getStatus() != 200) { + logger.warn("Error {} while sending command", result.getResponse().getReason()); } - }); - - } catch (UnsupportedEncodingException e) { - logger.warn("Error sending command", e); - } + } + }); } private void updateMain() throws IOException { diff --git a/bundles/org.openhab.binding.dscalarm/src/main/java/org/openhab/binding/dscalarm/internal/handler/IT100BridgeHandler.java b/bundles/org.openhab.binding.dscalarm/src/main/java/org/openhab/binding/dscalarm/internal/handler/IT100BridgeHandler.java index a9bfe980f..a552feed8 100644 --- a/bundles/org.openhab.binding.dscalarm/src/main/java/org/openhab/binding/dscalarm/internal/handler/IT100BridgeHandler.java +++ b/bundles/org.openhab.binding.dscalarm/src/main/java/org/openhab/binding/dscalarm/internal/handler/IT100BridgeHandler.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.TooManyListenersException; import org.openhab.binding.dscalarm.internal.config.IT100BridgeConfiguration; @@ -98,7 +99,7 @@ public class IT100BridgeHandler extends DSCAlarmBaseBridgeHandler implements Ser serialPort.enableReceiveThreshold(1); serialPort.disableReceiveTimeout(); - serialOutput = new OutputStreamWriter(serialPort.getOutputStream(), "US-ASCII"); + serialOutput = new OutputStreamWriter(serialPort.getOutputStream(), StandardCharsets.US_ASCII); serialInput = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); setSerialEventHandler(this); diff --git a/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/api/EcobeeApi.java b/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/api/EcobeeApi.java index 93c28d5e3..766ca4388 100644 --- a/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/api/EcobeeApi.java +++ b/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/api/EcobeeApi.java @@ -17,7 +17,6 @@ import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.*; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; @@ -268,10 +267,10 @@ public class EcobeeApi implements AccessTokenRefreshListener { return executePost(ECOBEE_THERMOSTAT_UPDATE_URL, GSON.toJson(request, ThermostatUpdateRequestDTO.class)); } - private String buildQueryUrl(String baseUrl, String requestJson) throws UnsupportedEncodingException { + private String buildQueryUrl(String baseUrl, String requestJson) { final StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append("?json="); - urlBuilder.append(URLEncoder.encode(requestJson, StandardCharsets.UTF_8.toString())); + urlBuilder.append(URLEncoder.encode(requestJson, StandardCharsets.UTF_8)); return urlBuilder.toString(); } diff --git a/bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/api/EvohomeApiClient.java b/bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/api/EvohomeApiClient.java index af9caf58b..8f80c8793 100644 --- a/bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/api/EvohomeApiClient.java +++ b/bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/api/EvohomeApiClient.java @@ -12,8 +12,8 @@ */ package org.openhab.binding.evohome.internal.api; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashMap; import java.util.Map; @@ -200,17 +200,9 @@ public class EvohomeApiClient { } private boolean authenticateWithUsername() { - boolean result = false; - - try { - String credentials = "Username=" + URLEncoder.encode(configuration.username, "UTF-8") + "&" + "Password=" - + URLEncoder.encode(configuration.password, "UTF-8"); - result = authenticate(credentials, "password"); - } catch (UnsupportedEncodingException e) { - logger.error("Credential conversion failed", e); - } - - return result; + String credentials = "Username=" + URLEncoder.encode(configuration.username, StandardCharsets.UTF_8) + "&" + + "Password=" + URLEncoder.encode(configuration.password, StandardCharsets.UTF_8); + return authenticate(credentials, "password"); } private boolean authenticateWithToken(String accessToken) { diff --git a/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/FoobotApiConnector.java b/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/FoobotApiConnector.java index 48e12ed58..8fb303f3c 100644 --- a/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/FoobotApiConnector.java +++ b/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/FoobotApiConnector.java @@ -14,7 +14,6 @@ package org.openhab.binding.foobot.internal; import static org.openhab.binding.foobot.internal.FoobotBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -92,12 +91,12 @@ public class FoobotApiConnector { public synchronized List getAssociatedDevices(String username) throws FoobotApiException { try { final String url = URL_TO_FETCH_DEVICES.replace("%username%", - URLEncoder.encode(username, StandardCharsets.UTF_8.toString())); + URLEncoder.encode(username, StandardCharsets.UTF_8)); logger.debug("URL = {}", url); List foobotDevices = GSON.fromJson(request(url, apiKey), FOOTBOT_DEVICE_LIST_TYPE); return Objects.requireNonNull(foobotDevices); - } catch (JsonParseException | UnsupportedEncodingException e) { + } catch (JsonParseException e) { throw new FoobotApiException(0, e.getMessage()); } } @@ -112,11 +111,11 @@ public class FoobotApiConnector { public synchronized @Nullable FoobotJsonData getSensorData(String uuid) throws FoobotApiException { try { final String url = URL_TO_FETCH_SENSOR_DATA.replace("%uuid%", - URLEncoder.encode(uuid, StandardCharsets.UTF_8.toString())); + URLEncoder.encode(uuid, StandardCharsets.UTF_8)); logger.debug("URL = {}", url); return GSON.fromJson(request(url, apiKey), FoobotJsonData.class); - } catch (JsonParseException | UnsupportedEncodingException e) { + } catch (JsonParseException e) { throw new FoobotApiException(0, e.getMessage()); } } diff --git a/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/api/FreeboxApiManager.java b/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/api/FreeboxApiManager.java index c2b84ad9e..deba7d677 100644 --- a/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/api/FreeboxApiManager.java +++ b/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/api/FreeboxApiManager.java @@ -15,7 +15,6 @@ package org.openhab.binding.freebox.internal.api; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; @@ -470,11 +469,7 @@ public class FreeboxApiManager { } private String encodeUrl(String url) throws FreeboxException { - try { - return URLEncoder.encode(url, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new FreeboxException("Encoding the URL \"" + url + "\" in UTF-8 failed", e); - } + return URLEncoder.encode(url, StandardCharsets.UTF_8); } public static String hmacSha1(String key, String value) throws FreeboxException { diff --git a/bundles/org.openhab.binding.globalcache/src/main/java/org/openhab/binding/globalcache/internal/handler/GlobalCacheHandler.java b/bundles/org.openhab.binding.globalcache/src/main/java/org/openhab/binding/globalcache/internal/handler/GlobalCacheHandler.java index 119fb83d0..3d0f9a882 100644 --- a/bundles/org.openhab.binding.globalcache/src/main/java/org/openhab/binding/globalcache/internal/handler/GlobalCacheHandler.java +++ b/bundles/org.openhab.binding.globalcache/src/main/java/org/openhab/binding/globalcache/internal/handler/GlobalCacheHandler.java @@ -20,7 +20,6 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; @@ -29,6 +28,7 @@ import java.net.SocketException; import java.net.URLDecoder; import java.net.URLEncoder; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -91,9 +91,6 @@ public class GlobalCacheHandler extends BaseThingHandler { // IR transaction counter private AtomicInteger irCounter; - // Character set to use for URL encoding & decoding - private String CHARSET = "ISO-8859-1"; - public GlobalCacheHandler(@NonNull Thing gcDevice, String ipv4Address) { super(gcDevice); irCounter = new AtomicInteger(1); @@ -578,7 +575,8 @@ public class GlobalCacheHandler extends BaseThingHandler { } byte[] deviceCommand; - deviceCommand = URLDecoder.decode(requestMessage.getDeviceCommand(), CHARSET).getBytes(CHARSET); + deviceCommand = URLDecoder.decode(requestMessage.getDeviceCommand(), StandardCharsets.ISO_8859_1) + .getBytes(StandardCharsets.ISO_8859_1); logger.debug("Writing decoded deviceCommand byte array: {}", getAsHexString(deviceCommand)); out.write(deviceCommand); @@ -912,14 +910,8 @@ public class GlobalCacheHandler extends BaseThingHandler { String endOfMessageString = (String) thing.getConfiguration().get(endOfMessageDelimiterConfig); if (endOfMessageString != null && !endOfMessageString.isEmpty()) { logger.debug("End of message is {} for thing {} {}", endOfMessageString, thingID(), serialDevice); - byte[] endOfMessage; - try { - endOfMessage = URLDecoder.decode(endOfMessageString, CHARSET).getBytes(CHARSET); - } catch (UnsupportedEncodingException e) { - logger.info("Unable to decode end of message delimiter {} for thing {} {}", endOfMessageString, - thingID(), serialDevice); - return null; - } + byte[] endOfMessage = URLDecoder.decode(endOfMessageString, StandardCharsets.ISO_8859_1) + .getBytes(StandardCharsets.ISO_8859_1); // Start the serial reader using the above end-of-message delimiter SerialPortReader serialPortReader = new SerialPortReader(serialDevice, getSerialIn(serialDevice), @@ -1003,9 +995,6 @@ public class GlobalCacheHandler extends BaseThingHandler { logger.debug("Rcv data from {} at {}:{}: {}", thingID(), getIP(), serialPort, getAsHexString(buffer)); updateFeedbackChannel(buffer); - } catch (UnsupportedEncodingException e) { - logger.info("Unsupported encoding exception: {}", e.getMessage(), e); - continue; } catch (IOException e) { logger.debug("Serial Reader got IOException: {}", e.getMessage()); break; @@ -1071,13 +1060,10 @@ public class GlobalCacheHandler extends BaseThingHandler { Channel channel = getThing().getChannel(channelId); if (channel != null && isLinked(channelId)) { logger.debug("Updating feedback channel for port {}", serialPort); - try { - String encodedReply = URLEncoder.encode(new String(buffer, CHARSET), CHARSET); - logger.debug("encodedReply='{}'", encodedReply); - updateState(channel.getUID(), new StringType(encodedReply)); - } catch (UnsupportedEncodingException e) { - logger.warn("Exception while encoding data read from serial device: {}", e.getMessage()); - } + String encodedReply = URLEncoder.encode(new String(buffer, StandardCharsets.ISO_8859_1), + StandardCharsets.ISO_8859_1); + logger.debug("encodedReply='{}'", encodedReply); + updateState(channel.getUID(), new StringType(encodedReply)); } } } diff --git a/bundles/org.openhab.binding.groheondus/src/main/java/org/openhab/binding/groheondus/internal/AccountServlet.java b/bundles/org.openhab.binding.groheondus/src/main/java/org/openhab/binding/groheondus/internal/AccountServlet.java index dd2784082..93d95fc88 100644 --- a/bundles/org.openhab.binding.groheondus/src/main/java/org/openhab/binding/groheondus/internal/AccountServlet.java +++ b/bundles/org.openhab.binding.groheondus/src/main/java/org/openhab/binding/groheondus/internal/AccountServlet.java @@ -13,7 +13,6 @@ package org.openhab.binding.groheondus.internal; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -55,8 +54,8 @@ public class AccountServlet extends HttpServlet { } } - private String servletUrl() throws UnsupportedEncodingException { - return "/groheondus/" + URLEncoder.encode(bridgeId, StandardCharsets.UTF_8.name()); + private String servletUrl() { + return "/groheondus/" + URLEncoder.encode(bridgeId, StandardCharsets.UTF_8); } @Override @@ -130,10 +129,6 @@ public class AccountServlet extends HttpServlet { } public void dispose() { - try { - httpService.unregister(servletUrl()); - } catch (UnsupportedEncodingException e) { - logger.warn("Unregistration of servlet failed", e); - } + httpService.unregister(servletUrl()); } } diff --git a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java index 04c205978..ef62b2f97 100644 --- a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java +++ b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java @@ -15,7 +15,7 @@ package org.openhab.binding.haassohnpelletstove.internal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.Properties; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -115,16 +115,12 @@ public class HaasSohnpelletstoveJSONCommunication { if (postData != null) { try { - InputStream targetStream = new ByteArrayInputStream(postData.getBytes("UTF-8")); + InputStream targetStream = new ByteArrayInputStream(postData.getBytes(StandardCharsets.UTF_8)); refreshOvenConnection(helper, thingUID); httpHeader = createHeader(postData); response = HttpUtil.executeUrl("POST", urlStr, httpHeader, targetStream, "application/json", 10000); resultOk = true; logger.debug("Execute POST request with content to {} with header: {}", urlStr, httpHeader.toString()); - } catch (UnsupportedEncodingException e1) { - logger.debug("Wrong encoding found. Only UTF-8 is supported."); - statusDescr = "Encoding of oven is not supported. Only UTF-8 is supported."; - resultOk = false; } catch (IOException e) { logger.debug("Error processiong POST request {}", urlStr); statusDescr = "Cannot execute command on Stove. Please verify connection and Thing Status"; @@ -161,9 +157,8 @@ public class HaasSohnpelletstoveJSONCommunication { * Creates the header for the Post Request * * @return The created Header Properties - * @throws UnsupportedEncodingException */ - private Properties createHeader(@Nullable String postData) throws UnsupportedEncodingException { + private Properties createHeader(@Nullable String postData) { Properties httpHeader = new Properties(); httpHeader.setProperty("Host", config.hostIP); httpHeader.setProperty("Accept", "*/*"); @@ -174,7 +169,7 @@ public class HaasSohnpelletstoveJSONCommunication { httpHeader.setProperty("token", "32 bytes"); httpHeader.setProperty("Content-Type", "application/json"); if (postData != null) { - int a = postData.getBytes("UTF-8").length; + int a = postData.getBytes(StandardCharsets.UTF_8).length; httpHeader.setProperty(xhspin, Integer.toString(a)); } httpHeader.setProperty("User-Agent", "ios"); diff --git a/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/API.java b/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/API.java index c7ca5d86a..5da791546 100644 --- a/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/API.java +++ b/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/API.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.hccrubbishcollection.internal; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; @@ -60,7 +59,7 @@ public class API { /** * Create a new API class. - * + * * @param httpClient The common http client provided from openHAB. * @param address The address of the premises. */ @@ -71,12 +70,12 @@ public class API { /** * Connects to the web service and gets the data. - * + * * @return boolean Success. */ public boolean update() { try { - final String url = REQUEST_URL + URLEncoder.encode(address, StandardCharsets.UTF_8.toString()); + final String url = REQUEST_URL + URLEncoder.encode(address, StandardCharsets.UTF_8); logger.debug("Fetching data from URL {} (address hidden)", REQUEST_URL); @@ -131,10 +130,6 @@ public class API { errorDetailMessage = "HTTP Code " + response.getStatus(); return false; } - } catch (UnsupportedEncodingException ue) { - errorDetail = ThingStatusDetail.COMMUNICATION_ERROR; - errorDetailMessage = "Encoding not supported!"; - return false; } catch (TimeoutException to) { errorDetail = ThingStatusDetail.COMMUNICATION_ERROR; errorDetailMessage = "Response Timeout (will try again soon)"; @@ -146,7 +141,7 @@ public class API { /** * Returns the last request status. - * + * * @return ThingStatusDetail The openHAB error type. */ public ThingStatusDetail getErrorDetail() { @@ -155,7 +150,7 @@ public class API { /** * Gets the error, if occurred. - * + * * @return String The error message. */ public String getErrorDetailMessage() { @@ -164,7 +159,7 @@ public class API { /** * The collection week. - * + * * @return Integer The week number. */ public @Nullable Integer getCollectionWeek() { @@ -173,7 +168,7 @@ public class API { /** * Gets the collection day of week. - * + * * @return Integer The day of the week. 1 = Monday. */ public @Nullable Integer getDay() { @@ -182,7 +177,7 @@ public class API { /** * The upcoming recycling collection date. - * + * * @return ZonedDateTime */ public @Nullable ZonedDateTime getRecyclingDate() { @@ -191,7 +186,7 @@ public class API { /** * The upcoming general rubbish collection date. - * + * * @return ZonedDateTime */ public @Nullable ZonedDateTime getGeneralDate() { diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/json/HeosJsonParser.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/json/HeosJsonParser.java index 85b1934e9..e6332354c 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/json/HeosJsonParser.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/json/HeosJsonParser.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.heos.internal.json; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -90,10 +89,6 @@ public class HeosJsonParser { } private static String decode(String encoded) { - try { - return URLDecoder.decode(encoded, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("Impossible: UTF-8 is a required encoding", e); - } + return URLDecoder.decode(encoded, StandardCharsets.UTF_8); } } diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/HeosCommands.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/HeosCommands.java index e12d48ab3..16d1f2199 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/HeosCommands.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/HeosCommands.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.heos.internal.resources; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -322,12 +321,8 @@ public class HeosCommands { } private static String urlEncode(String username) { - try { - String encoded = URLEncoder.encode(username, StandardCharsets.UTF_8.toString()); - // however it cannot handle escaped @ signs - return encoded.replace("%40", "@"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 is not supported, bailing out"); - } + String encoded = URLEncoder.encode(username, StandardCharsets.UTF_8); + // however it cannot handle escaped @ signs + return encoded.replace("%40", "@"); } } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java index 4d20f99cd..0c686b4f7 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java @@ -12,6 +12,9 @@ */ package org.openhab.binding.homematic.internal.common; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + import org.openhab.binding.homematic.internal.model.HmChannel; import org.openhab.binding.homematic.internal.model.HmGatewayInfo; import org.openhab.binding.homematic.internal.model.HmInterface; @@ -22,9 +25,6 @@ import org.openhab.binding.homematic.internal.model.HmInterface; * @author Gerhard Riegler - Initial contribution */ public class HomematicConfig { - private static final String ISO_ENCODING = "ISO-8859-1"; - private static final String UTF_ENCODING = "UTF-8"; - private static final String GATEWAY_TYPE_AUTO = "AUTO"; private static final String GATEWAY_TYPE_CCU = "CCU"; private static final String GATEWAY_TYPE_NOCCU = "NOCCU"; @@ -363,11 +363,11 @@ public class HomematicConfig { /** * Returns the encoding that is suitable on requests to & responds from the Homematic gateway. */ - public String getEncoding() { + public Charset getEncoding() { if (gatewayInfo != null && gatewayInfo.isHomegear()) { - return UTF_ENCODING; + return StandardCharsets.UTF_8; } else { - return ISO_ENCODING; + return StandardCharsets.ISO_8859_1; } } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java index a94f38d2d..14ee71f53 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java @@ -19,6 +19,7 @@ import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; +import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; @@ -52,16 +53,16 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { private String methodName; private TYPE type; private int args; - private String encoding; + private Charset encoding; - public BinRpcMessage(String methodName, String encoding) { + public BinRpcMessage(String methodName, Charset encoding) { this(methodName, TYPE.REQUEST, encoding); } /** * Creates a new request with the specified methodName. */ - public BinRpcMessage(String methodName, TYPE type, String encoding) { + public BinRpcMessage(String methodName, TYPE type, Charset encoding) { this.methodName = methodName; this.type = type; this.encoding = encoding; @@ -71,7 +72,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { /** * Decodes a BIN-RPC message from the given InputStream. */ - public BinRpcMessage(InputStream is, boolean methodHeader, String encoding) throws IOException { + public BinRpcMessage(InputStream is, boolean methodHeader, Charset encoding) throws IOException { this.encoding = encoding; byte sig[] = new byte[8]; int length = is.read(sig, 0, 4); @@ -111,7 +112,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { /** * Decodes a BIN-RPC message from the given byte array. */ - public BinRpcMessage(byte[] message, boolean methodHeader, String encoding) throws IOException, ParseException { + public BinRpcMessage(byte[] message, boolean methodHeader, Charset encoding) throws IOException, ParseException { this.encoding = encoding; if (message.length < 8) { throw new EOFException("Only " + message.length + " bytes received"); @@ -213,7 +214,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { return (new BigInteger(bi)).longValue(); } - private String readString() throws UnsupportedEncodingException { + private String readString() { int len = readInt(); offset += len; return new String(binRpcData, offset - len, len, encoding); @@ -310,12 +311,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { } private void addString(String string) { - byte sd[]; - try { - sd = string.getBytes(encoding); - } catch (UnsupportedEncodingException use) { - sd = string.getBytes(); - } + byte sd[] = string.getBytes(encoding); for (byte ch : sd) { addByte(ch); } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java index 320c0097b..4b7732e21 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java @@ -14,6 +14,7 @@ package org.openhab.binding.homematic.internal.communicator.message; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.Base64; @@ -43,7 +44,7 @@ public class XmlRpcResponse implements RpcResponse { /** * Decodes a XML-RPC message from the given InputStream. */ - public XmlRpcResponse(InputStream is, String encoding) + public XmlRpcResponse(InputStream is, Charset encoding) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); @@ -51,7 +52,7 @@ public class XmlRpcResponse implements RpcResponse { saxParser.getXMLReader().setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); InputSource inputSource = new InputSource(is); - inputSource.setEncoding(encoding); + inputSource.setEncoding(encoding.name()); saxParser.parse(inputSource, new XmlRpcHandler()); } diff --git a/bundles/org.openhab.binding.ihc/src/test/java/org/openhab/binding/ihc/internal/ws/IhcClientTest.java b/bundles/org.openhab.binding.ihc/src/test/java/org/openhab/binding/ihc/internal/ws/IhcClientTest.java index e7fc4d1d8..64a1b2500 100644 --- a/bundles/org.openhab.binding.ihc/src/test/java/org/openhab/binding/ihc/internal/ws/IhcClientTest.java +++ b/bundles/org.openhab.binding.ihc/src/test/java/org/openhab/binding/ihc/internal/ws/IhcClientTest.java @@ -12,11 +12,11 @@ */ package org.openhab.binding.ihc.internal.ws; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; -import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -57,10 +57,10 @@ public class IhcClientTest { } @Test - public void loadProjectFileFromControllerTest() throws IhcExecption, UnsupportedEncodingException { + public void loadProjectFileFromControllerTest() throws IhcExecption { final String expectedFileContent = ResourceFileUtils.getFileContent("ProjectFileContent.txt"); final byte[] result = ihcClient.getProjectFileFromController(); - assertEquals(expectedFileContent, new String(result, "UTF-8")); + assertEquals(expectedFileContent, new String(result, StandardCharsets.UTF_8)); } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java index a66ee4d32..8de945f4e 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java @@ -12,11 +12,11 @@ */ package org.openhab.binding.ipcamera.internal; -import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Enumeration; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -111,12 +111,7 @@ public class Helper { * @author Matthew Skinner - Initial contribution */ public static String encodeSpecialChars(String text) { - String processed = text; - try { - processed = URLEncoder.encode(text, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException e) { - } - return processed; + return URLEncoder.encode(text, StandardCharsets.UTF_8).replace("+", "%20"); } public static String getLocalIpAddress() { diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java index f5c2b1f4d..f069be0a0 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java @@ -14,7 +14,6 @@ package org.openhab.binding.ipcamera.internal.onvif; import static org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -503,10 +502,9 @@ public class OnvifConnection { try { msgDigest = MessageDigest.getInstance("SHA-1"); msgDigest.reset(); - msgDigest.update(beforeEncryption.getBytes("utf8")); + msgDigest.update(beforeEncryption.getBytes(StandardCharsets.UTF_8)); encryptedRaw = msgDigest.digest(); } catch (NoSuchAlgorithmException e) { - } catch (UnsupportedEncodingException e) { } return Base64.getEncoder().encodeToString(encryptedRaw); } diff --git a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java index ed9f53e48..188207203 100644 --- a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java +++ b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java @@ -13,7 +13,6 @@ package org.openhab.binding.kodi.internal.protocol; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; @@ -857,16 +856,11 @@ public class KodiConnection implements KodiClientSocketEventListener { } private @Nullable String stripImageUrl(String url) { - try { - // we have to strip ending "/" here because Kodi returns a not valid path and filename - // "fanart":"image://http%3a%2f%2fthetvdb.com%2fbanners%2ffanart%2foriginal%2f263365-31.jpg/" - // "thumbnail":"image://http%3a%2f%2fthetvdb.com%2fbanners%2fepisodes%2f263365%2f5640869.jpg/" - String encodedURL = URLEncoder.encode(stripEnd(url, '/'), StandardCharsets.UTF_8.name()); - return imageUri.resolve(encodedURL).toString(); - } catch (UnsupportedEncodingException e) { - logger.debug("exception during encoding {}", url, e); - return null; - } + // we have to strip ending "/" here because Kodi returns a not valid path and filename + // "fanart":"image://http%3a%2f%2fthetvdb.com%2fbanners%2ffanart%2foriginal%2f263365-31.jpg/" + // "thumbnail":"image://http%3a%2f%2fthetvdb.com%2fbanners%2fepisodes%2f263365%2f5640869.jpg/" + String encodedURL = URLEncoder.encode(stripEnd(url, '/'), StandardCharsets.UTF_8); + return imageUri.resolve(encodedURL).toString(); } private String stripEnd(final String str, final char suffix) { diff --git a/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/thirdgeneration/ThirdGenerationHandler.java b/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/thirdgeneration/ThirdGenerationHandler.java index 6104cdd6f..fe34979ae 100644 --- a/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/thirdgeneration/ThirdGenerationHandler.java +++ b/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/thirdgeneration/ThirdGenerationHandler.java @@ -14,7 +14,7 @@ package org.openhab.binding.kostalinverter.internal.thirdgeneration; import static org.openhab.binding.kostalinverter.internal.thirdgeneration.ThirdGenerationBindingConstants.*; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -443,8 +443,8 @@ public class ThirdGenerationHandler extends BaseThingHandler { return; } try { - data = cipher.doFinal(token.getBytes("UTF-8")); - } catch (IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e1) { + data = cipher.doFinal(token.getBytes(StandardCharsets.UTF_8)); + } catch (IllegalBlockSizeException | BadPaddingException e1) { // No JSON answer received updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, COMMUNICATION_ERROR_JSON); return; diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/security/LxWsSecurityToken.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/security/LxWsSecurityToken.java index b9e54ec63..80b5c576e 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/security/LxWsSecurityToken.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/security/LxWsSecurityToken.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.loxone.internal.security; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; @@ -238,11 +237,7 @@ class LxWsSecurityToken extends LxWsSecurity { try { String encrypted = Base64.getEncoder() .encodeToString(aesEncryptCipher.doFinal(str.getBytes(StandardCharsets.UTF_8))); - try { - encrypted = URLEncoder.encode(encrypted, "UTF-8"); - } catch (UnsupportedEncodingException e) { - logger.warn("[{}] Unsupported encoding for encrypted command conversion to URL.", debugId); - } + encrypted = URLEncoder.encode(encrypted, StandardCharsets.UTF_8); return CMD_ENCRYPT_CMD + encrypted; } catch (IllegalBlockSizeException | BadPaddingException e) { logger.warn("[{}] Command encryption failed: {}", debugId, e.getMessage()); @@ -260,7 +255,7 @@ class LxWsSecurityToken extends LxWsSecurity { try { byte[] bytes = Base64.getDecoder().decode(string); bytes = aesDecryptCipher.doFinal(bytes); - string = new String(bytes, "UTF-8"); + string = new String(bytes, StandardCharsets.UTF_8); string = string.replaceAll("\0+.*$", ""); string = string.replaceFirst("^salt/[^/]*/", ""); string = string.replaceFirst("^nextSalt/[^/]*/[^/]*/", ""); @@ -269,8 +264,6 @@ class LxWsSecurityToken extends LxWsSecurity { logger.debug("[{}] Failed to decode base64 string: {}", debugId, string); } catch (IllegalBlockSizeException | BadPaddingException e) { logger.warn("[{}] Command decryption failed: {}", debugId, e.getMessage()); - } catch (UnsupportedEncodingException e) { - logger.warn("[{}] Unsupported encoding for decrypted bytes to string conversion.", debugId); } return string; } @@ -544,11 +537,7 @@ class LxWsSecurityToken extends LxWsSecurity { byte[] bytes = new byte[SALT_BYTES]; secureRandom.nextBytes(bytes); String salt = HexUtils.bytesToHex(bytes); - try { - salt = URLEncoder.encode(salt, "UTF-8"); - } catch (UnsupportedEncodingException e) { - logger.warn("[{}] Unsupported encoding for salt conversion to URL.", debugId); - } + salt = URLEncoder.encode(salt, StandardCharsets.UTF_8); saltTimeStamp = timeElapsedInSeconds(); saltUseCount = 0; logger.debug("[{}] Generated salt: {}", debugId, salt); diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java index 597bdfa76..357d33478 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.magentatv.internal; -import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Set; @@ -100,8 +99,6 @@ public class MagentaTVBindingConstants { public static final int DEF_REFRESH_INTERVAL_SEC = 60; public static final int NETWORK_TIMEOUT_MS = 3000; - public static final String UTF_8 = StandardCharsets.UTF_8.name(); - public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_HOST = "HOST"; public static final String HEADER_ACCEPT = "Accept"; diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java index 01a764bca..b665570b3 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java @@ -15,7 +15,7 @@ package org.openhab.binding.magentatv.internal.handler; import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.*; import static org.openhab.binding.magentatv.internal.MagentaTVUtil.*; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; @@ -480,7 +480,7 @@ public class MagentaTVControl { */ public static String computeMD5(String unhashed) { try { - byte[] bytesOfMessage = unhashed.getBytes(UTF_8); + byte[] bytesOfMessage = unhashed.getBytes(StandardCharsets.UTF_8); MessageDigest md5 = MessageDigest.getInstance(HASH_ALGORITHM_MD5); byte[] hash = md5.digest(bytesOfMessage); @@ -490,7 +490,7 @@ public class MagentaTVControl { } return sb.toString(); - } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { return ""; } } diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java index a95737f14..08369e057 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java @@ -16,6 +16,7 @@ import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.* import static org.openhab.binding.magentatv.internal.MagentaTVUtil.substringBetween; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Scanner; @@ -139,7 +140,7 @@ public class MagentaTVNotifyServlet extends HttpServlet { } finally { // send response if (response != null) { - response.setCharacterEncoding(UTF_8); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.getWriter().write(""); } } diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java index 3b020d7eb..0f71580e2 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java @@ -15,7 +15,6 @@ package org.openhab.binding.magentatv.internal.network; import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.*; import static org.openhab.binding.magentatv.internal.MagentaTVUtil.*; -import java.io.UnsupportedEncodingException; import java.net.HttpCookie; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -291,11 +290,6 @@ public class MagentaTVOAuth { } private String urlEncode(String url) { - try { - return URLEncoder.encode(url, UTF_8); - } catch (UnsupportedEncodingException e) { - logger.warn("OAuth: Unable to URL encode string {}", url, e); - return ""; - } + return URLEncoder.encode(url, StandardCharsets.UTF_8); } } diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/EncryptionHelper.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/EncryptionHelper.java index 16077ce82..3e8476f8c 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/EncryptionHelper.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/EncryptionHelper.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.mihome.internal; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -55,13 +55,7 @@ public class EncryptionHelper { logger.warn("Failed to construct Cipher"); return ""; } - SecretKeySpec keySpec; - try { - keySpec = new SecretKeySpec(key.getBytes("UTF8"), "AES"); - } catch (UnsupportedEncodingException e) { - logger.warn("Failed to construct SecretKeySpec"); - return ""; - } + SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); try { cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector); } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { diff --git a/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/MiIoCrypto.java b/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/MiIoCrypto.java index 46485221e..48d73845e 100644 --- a/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/MiIoCrypto.java +++ b/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/MiIoCrypto.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.miio.internal; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; @@ -99,11 +99,7 @@ public class MiIoCrypto { SecretKeySpec keySpec = new SecretKeySpec(new byte[16], "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decrypted = cipher.doFinal(cipherText); - try { - return new String(decrypted, "UTF-8").trim(); - } catch (UnsupportedEncodingException e) { - return new String(decrypted).trim(); - } + return new String(decrypted, StandardCharsets.UTF_8).trim(); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new MiIoCryptoException(e.getMessage(), e); diff --git a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java index c769bcae1..f5d63aa48 100644 --- a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java +++ b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java @@ -15,11 +15,11 @@ package org.openhab.binding.myq.internal.handler; import static org.openhab.binding.myq.internal.MyQBindingConstants.*; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.CookieStore; import java.net.HttpCookie; import java.net.URI; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; @@ -485,7 +485,7 @@ public class MyQAccountHandler extends BaseBridgeHandler implements AccessTokenR ContentResponse response = request.send(); logger.debug("Login Code {} Response {}", response.getStatus(), response.getContentAsString()); return response; - } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { throw new ExecutionException(e.getCause()); } } @@ -613,16 +613,15 @@ public class MyQAccountHandler extends BaseBridgeHandler implements AccessTokenR return sb.toString(); } - private String generateCodeVerifier() throws UnsupportedEncodingException { + private String generateCodeVerifier() { SecureRandom secureRandom = new SecureRandom(); byte[] codeVerifier = new byte[32]; secureRandom.nextBytes(codeVerifier); return Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifier); } - private String generateCodeChallange(String codeVerifier) - throws UnsupportedEncodingException, NoSuchAlgorithmException { - byte[] bytes = codeVerifier.getBytes("US-ASCII"); + private String generateCodeChallange(String codeVerifier) throws NoSuchAlgorithmException { + byte[] bytes = codeVerifier.getBytes(StandardCharsets.US_ASCII); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(bytes, 0, bytes.length); byte[] digest = messageDigest.digest(); diff --git a/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java b/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java index aa552e1a5..91309d9cd 100644 --- a/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java +++ b/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java @@ -22,7 +22,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -37,12 +37,12 @@ import com.google.gson.stream.JsonWriter; @NonNullByDefault public class SDMDataUtil { - public static Reader openDataReader(String fileName) throws UnsupportedEncodingException, FileNotFoundException { + public static Reader openDataReader(String fileName) throws FileNotFoundException { String packagePath = (SDMDataUtil.class.getPackage().getName()).replaceAll("\\.", "/"); String filePath = "src/test/resources/" + packagePath + "/" + fileName; InputStream inputStream = new FileInputStream(filePath); - return new InputStreamReader(inputStream, "UTF-8"); + return new InputStreamReader(inputStream, StandardCharsets.UTF_8); } public static T fromJson(String fileName, Class dataClass) throws IOException { diff --git a/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/connector/UplinkWebInterface.java b/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/connector/UplinkWebInterface.java index bd8bc6687..9c75259da 100644 --- a/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/connector/UplinkWebInterface.java +++ b/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/connector/UplinkWebInterface.java @@ -14,7 +14,6 @@ package org.openhab.binding.nibeuplink.internal.connector; import static org.openhab.binding.nibeuplink.internal.NibeUplinkBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.util.Queue; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -200,8 +199,6 @@ public class UplinkWebInterface implements AtomicReferenceTrait { /** * authenticates with the Nibe Uplink WEB interface - * - * @throws UnsupportedEncodingException */ private synchronized void authenticate() { setAuthenticated(false); diff --git a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxPanelSettings.java b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxPanelSettings.java index ba4ef1f53..7948fcbaf 100644 --- a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxPanelSettings.java +++ b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxPanelSettings.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.powermax.internal.state; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; @@ -364,11 +364,7 @@ public class PowermaxPanelSettings { break; default: if ((data[i] & 0x000000FF) >= 0x20) { - try { - result += new String(data, i, 1, "US-ASCII"); - } catch (UnsupportedEncodingException e) { - logger.debug("Unhandled character code {}", data[i]); - } + result += new String(data, i, 1, StandardCharsets.US_ASCII); } else { logger.debug("Unhandled character code {}", data[i]); } diff --git a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/discovery/RadioThermostatDiscoveryService.java b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/discovery/RadioThermostatDiscoveryService.java index 250f9251c..7356606c8 100644 --- a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/discovery/RadioThermostatDiscoveryService.java +++ b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/discovery/RadioThermostatDiscoveryService.java @@ -13,7 +13,6 @@ package org.openhab.binding.radiothermostat.internal.discovery; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.InetAddress; @@ -57,7 +56,6 @@ import com.google.gson.JsonSyntaxException; * @author Michael Lobstein - Cleanup for RadioThermostat * */ - @NonNullByDefault @Component(service = DiscoveryService.class, configurationPid = "discovery.radiothermostat") public class RadioThermostatDiscoveryService extends AbstractDiscoveryService { @@ -119,10 +117,8 @@ public class RadioThermostatDiscoveryService extends AbstractDiscoveryService { * @throws UnknownHostException * @throws IOException * @throws SocketException - * @throws UnsupportedEncodingException */ - private void sendDiscoveryBroacast(NetworkInterface ni) - throws UnknownHostException, SocketException, UnsupportedEncodingException { + private void sendDiscoveryBroacast(NetworkInterface ni) throws UnknownHostException, SocketException { InetAddress m = InetAddress.getByName("239.255.255.250"); final int port = 1900; logger.debug("Sending discovery broadcast"); @@ -153,7 +149,7 @@ public class RadioThermostatDiscoveryService extends AbstractDiscoveryService { socket.setNetworkInterface(ni); socket.joinGroup(m); logger.debug("Joined UPnP Multicast group on Interface: {}", ni.getName()); - byte[] requestMessage = RADIOTHERMOSTAT_DISCOVERY_MESSAGE.getBytes("UTF-8"); + byte[] requestMessage = RADIOTHERMOSTAT_DISCOVERY_MESSAGE.getBytes(StandardCharsets.UTF_8); DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, m, port); socket.send(datagramPacket); try { diff --git a/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/model/cmd/NameCommand.java b/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/model/cmd/NameCommand.java index 937c89158..39c87545e 100644 --- a/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/model/cmd/NameCommand.java +++ b/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/model/cmd/NameCommand.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.robonect.internal.model.cmd; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -22,7 +21,7 @@ import org.slf4j.LoggerFactory; /** * The command allows to set or retrieve the mower name. - * + * * @author Marco Meyer - Initial contribution */ public class NameCommand implements Command { @@ -33,7 +32,7 @@ public class NameCommand implements Command { /** * sets the mower name. - * + * * @param newName - the mower name. * @return - the command instance. */ @@ -52,13 +51,7 @@ public class NameCommand implements Command { if (newName == null) { return baseURL + "?cmd=name"; } else { - try { - return baseURL + "?cmd=name&name=" - + URLEncoder.encode(newName, StandardCharsets.ISO_8859_1.displayName()); - } catch (UnsupportedEncodingException e) { - logger.error("Could not encode name {} ", newName, e); - return baseURL + "?cmd=name"; - } + return baseURL + "?cmd=name&name=" + URLEncoder.encode(newName, StandardCharsets.ISO_8859_1); } } } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java index d37b4a4ee..1297c0d0e 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java @@ -14,7 +14,6 @@ package org.openhab.binding.shelly.internal.util; import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.URLEncoder; @@ -271,11 +270,7 @@ public class ShellyUtils { } public static String urlEncode(String input) { - try { - return URLEncoder.encode(input, StandardCharsets.UTF_8.toString()); - } catch (UnsupportedEncodingException e) { - return input; - } + return URLEncoder.encode(input, StandardCharsets.UTF_8); } public static Long now() { diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDataPoints.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDataPoints.java index 8f25872a3..76733a8d6 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDataPoints.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDataPoints.java @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; @@ -129,8 +128,7 @@ public class RdsDataPoints { * private method: execute an HTTP PUT on the server to set a data point value */ private void httpSetPointValueJson(String apiKey, String token, String pointUrl, String json) - throws RdsCloudException, UnsupportedEncodingException, ProtocolException, MalformedURLException, - IOException { + throws RdsCloudException, ProtocolException, MalformedURLException, IOException { /* * NOTE: this class uses JAVAX HttpsURLConnection library instead of the * preferred JETTY library; the reason is that JETTY does not allow sending the diff --git a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/connector/WebInterface.java b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/connector/WebInterface.java index c17565cb5..944369f27 100644 --- a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/connector/WebInterface.java +++ b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/connector/WebInterface.java @@ -14,7 +14,6 @@ package org.openhab.binding.solaredge.internal.connector; import static org.openhab.binding.solaredge.internal.SolarEdgeBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.util.Queue; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -193,8 +192,6 @@ public class WebInterface implements AtomicReferenceTrait { /** * authenticates with the Solaredge WEB interface - * - * @throws UnsupportedEncodingException */ private synchronized void authenticate() { setAuthenticated(false); diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java index e722b74ca..26e89f2b8 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.somfytahoma.internal.handler; import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -282,11 +281,7 @@ public class SomfyTahomaBridgeHandler extends BaseBridgeHandler { } private String urlEncode(String text) { - try { - return URLEncoder.encode(text, StandardCharsets.UTF_8.toString()); - } catch (UnsupportedEncodingException e) { - return text; - } + return URLEncoder.encode(text, StandardCharsets.UTF_8); } private void enableLogin() { diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java index a0e5f4c97..e6a14dce3 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java @@ -19,7 +19,6 @@ import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.URLDecoder; import java.net.URLEncoder; @@ -91,9 +90,6 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { // time in seconds to try to reconnect private static final int RECONNECT_TIME = 60; - // utf8 charset name - private static final String UTF8_NAME = StandardCharsets.UTF_8.name(); - // the value by which the volume is changed by each INCREASE or // DECREASE-Event private static final int VOLUME_CHANGE_SIZE = 5; @@ -520,21 +516,11 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } private String decode(String raw) { - try { - return URLDecoder.decode(raw, UTF8_NAME); - } catch (UnsupportedEncodingException e) { - logger.debug("Failed to decode '{}' ", raw, e); - return null; - } + return URLDecoder.decode(raw, StandardCharsets.UTF_8); } private String encode(String raw) { - try { - return URLEncoder.encode(raw, UTF8_NAME); - } catch (UnsupportedEncodingException e) { - logger.debug("Failed to encode '{}' ", raw, e); - return null; - } + return URLEncoder.encode(raw, StandardCharsets.UTF_8); } @NonNullByDefault diff --git a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java index d865f95ce..25a4677e1 100644 --- a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java +++ b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java @@ -14,7 +14,6 @@ package org.openhab.binding.touchwand.internal; import static org.openhab.binding.touchwand.internal.TouchWandBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.net.CookieManager; import java.net.MalformedURLException; import java.net.URL; @@ -104,18 +103,11 @@ public class TouchWandRestClient { } private final boolean cmdLogin(String user, String pass, String ipAddr) { - String encodedUser; - String encodedPass; + String encodedUser = URLEncoder.encode(user, StandardCharsets.UTF_8); + String encodedPass = URLEncoder.encode(pass, StandardCharsets.UTF_8); String response = ""; - - try { - encodedUser = URLEncoder.encode(user, StandardCharsets.UTF_8.toString()); - encodedPass = URLEncoder.encode(pass, StandardCharsets.UTF_8.toString()); - String command = buildUrl(CMD_LOGIN) + "user=" + encodedUser + "&" + "psw=" + encodedPass; - response = sendCommand(command, METHOD_GET, ""); - } catch (UnsupportedEncodingException e) { - logger.warn("Error url encoding username or password : {}", e.getMessage()); - } + String command = buildUrl(CMD_LOGIN) + "user=" + encodedUser + "&" + "psw=" + encodedPass; + response = sendCommand(command, METHOD_GET, ""); return !response.equals("Unauthorized"); } diff --git a/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpRendererHandler.java b/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpRendererHandler.java index 79b82d6f2..7265d28a8 100644 --- a/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpRendererHandler.java +++ b/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpRendererHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.upnpcontrol.internal.handler; import static org.openhab.binding.upnpcontrol.internal.UpnpControlBindingConstants.*; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -411,22 +410,18 @@ public class UpnpRendererHandler extends UpnpHandler { */ public void setCurrentURI(String URI, String URIMetaData) { String uri = ""; - try { - uri = URLDecoder.decode(URI.trim(), StandardCharsets.UTF_8.name()); - // Some renderers don't send a URI Last Changed event when the same URI is requested, so don't wait for it - // before starting to play - if (!uri.equals(nowPlayingUri) && !playingNotification) { - CompletableFuture settingURI = isSettingURI; - if (settingURI != null) { - settingURI.complete(false); - } - isSettingURI = new CompletableFuture(); // set this so we don't start playing when not finished - // setting URI - } else { - logger.debug("New URI {} is same as previous on renderer {}", nowPlayingUri, thing.getLabel()); + uri = URLDecoder.decode(URI.trim(), StandardCharsets.UTF_8); + // Some renderers don't send a URI Last Changed event when the same URI is requested, so don't wait for it + // before starting to play + if (!uri.equals(nowPlayingUri) && !playingNotification) { + CompletableFuture settingURI = isSettingURI; + if (settingURI != null) { + settingURI.complete(false); } - } catch (UnsupportedEncodingException ignore) { - uri = URI; + isSettingURI = new CompletableFuture(); // set this so we don't start playing when not finished + // setting URI + } else { + logger.debug("New URI {} is same as previous on renderer {}", nowPlayingUri, thing.getLabel()); } Map inputs = new HashMap<>(); @@ -1244,18 +1239,14 @@ public class UpnpRendererHandler extends UpnpHandler { String uri = ""; String currentUri = ""; String nextUri = ""; - try { - if (value != null) { - uri = URLDecoder.decode(value.trim(), StandardCharsets.UTF_8.name()); - } - if (current != null) { - currentUri = URLDecoder.decode(current.getRes().trim(), StandardCharsets.UTF_8.name()); - } - if (next != null) { - nextUri = URLDecoder.decode(next.getRes(), StandardCharsets.UTF_8.name()); - } - } catch (UnsupportedEncodingException ignore) { - // If not valid current URI, we assume there is none + if (value != null) { + uri = URLDecoder.decode(value.trim(), StandardCharsets.UTF_8); + } + if (current != null) { + currentUri = URLDecoder.decode(current.getRes().trim(), StandardCharsets.UTF_8); + } + if (next != null) { + nextUri = URLDecoder.decode(next.getRes(), StandardCharsets.UTF_8); } if (playingNotification && uri.equals(notificationUri)) { @@ -1635,15 +1626,9 @@ public class UpnpRendererHandler extends UpnpHandler { String mediaRes = media.getRes().trim(); String entryRes = (entry != null) ? entry.getRes().trim() : ""; - try { - String mediaUrl = URLDecoder.decode(mediaRes, StandardCharsets.UTF_8.name()); - String entryUrl = URLDecoder.decode(entryRes, StandardCharsets.UTF_8.name()); - isCurrent = mediaUrl.equals(entryUrl); - } catch (UnsupportedEncodingException e) { - logger.debug("Renderer {} unsupported encoding for new {} or current {} res URL, trying string compare", - thing.getLabel(), mediaRes, entryRes); - isCurrent = mediaRes.equals(entryRes); - } + String mediaUrl = URLDecoder.decode(mediaRes, StandardCharsets.UTF_8); + String entryUrl = URLDecoder.decode(entryRes, StandardCharsets.UTF_8); + isCurrent = mediaUrl.equals(entryUrl); logger.trace("Current queue res: {}", entryRes); logger.trace("Updated media res: {}", mediaRes); diff --git a/bundles/org.openhab.binding.venstarthermostat/src/main/java/org/openhab/binding/venstarthermostat/internal/discovery/VenstarThermostatDiscoveryService.java b/bundles/org.openhab.binding.venstarthermostat/src/main/java/org/openhab/binding/venstarthermostat/internal/discovery/VenstarThermostatDiscoveryService.java index 60c66153b..38ede5416 100644 --- a/bundles/org.openhab.binding.venstarthermostat/src/main/java/org/openhab/binding/venstarthermostat/internal/discovery/VenstarThermostatDiscoveryService.java +++ b/bundles/org.openhab.binding.venstarthermostat/src/main/java/org/openhab/binding/venstarthermostat/internal/discovery/VenstarThermostatDiscoveryService.java @@ -13,7 +13,6 @@ package org.openhab.binding.venstarthermostat.internal.discovery; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.InetAddress; @@ -22,6 +21,7 @@ import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; import java.util.Enumeration; import java.util.Scanner; import java.util.concurrent.ScheduledFuture; @@ -114,10 +114,9 @@ public class VenstarThermostatDiscoveryService extends AbstractDiscoveryService * @throws UnknownHostException * @throws IOException * @throws SocketException - * @throws UnsupportedEncodingException */ private @Nullable MulticastSocket sendDiscoveryBroacast(NetworkInterface ni) - throws UnknownHostException, SocketException, UnsupportedEncodingException { + throws UnknownHostException, SocketException { InetAddress m = InetAddress.getByName("239.255.255.250"); final int port = 1900; @@ -154,7 +153,7 @@ public class VenstarThermostatDiscoveryService extends AbstractDiscoveryService socket.joinGroup(m); logger.trace("Joined UPnP Multicast group on Interface: {}", ni.getName()); - byte[] requestMessage = COLOR_TOUCH_DISCOVERY_MESSAGE.getBytes("UTF-8"); + byte[] requestMessage = COLOR_TOUCH_DISCOVERY_MESSAGE.getBytes(StandardCharsets.UTF_8); DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, m, port); socket.send(datagramPacket); return socket; diff --git a/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/handler/ZmAuth.java b/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/handler/ZmAuth.java index 890dc9a11..dd791c02a 100644 --- a/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/handler/ZmAuth.java +++ b/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/handler/ZmAuth.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.zoneminder.internal.handler; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -61,14 +60,8 @@ public class ZmAuth { logger.debug("ZmAuth: Authorization is enabled"); usingAuthorization = true; isAuthorized = false; - String encodedUser = null; - String encodedPass = null; - try { - encodedUser = URLEncoder.encode(user, StandardCharsets.UTF_8.name()); - encodedPass = URLEncoder.encode(pass, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - logger.warn("ZmAuth: Unable to encode user name and password"); - } + String encodedUser = URLEncoder.encode(user, StandardCharsets.UTF_8); + String encodedPass = URLEncoder.encode(pass, StandardCharsets.UTF_8); authContent = encodedUser == null ? "" : String.format("user=%s&pass=%s&stateful=1", encodedUser, encodedPass); } diff --git a/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceActionHandler.java b/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceActionHandler.java index 04345c374..9e718b4e5 100644 --- a/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceActionHandler.java +++ b/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceActionHandler.java @@ -12,8 +12,8 @@ */ package org.openhab.io.imperihome.internal.handler; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import javax.servlet.http.HttpServletRequest; @@ -30,8 +30,6 @@ import org.slf4j.LoggerFactory; */ public class DeviceActionHandler { - private static final String CHARSET = "UTF-8"; - private final Logger logger = LoggerFactory.getLogger(DeviceActionHandler.class); private final DeviceRegistry deviceRegistry; @@ -42,17 +40,13 @@ public class DeviceActionHandler { public void handle(HttpServletRequest req, Matcher urlMatcher) { String deviceId, action, value; - try { - deviceId = URLDecoder.decode(urlMatcher.group(1), CHARSET); - action = URLDecoder.decode(urlMatcher.group(2), CHARSET); + deviceId = URLDecoder.decode(urlMatcher.group(1), StandardCharsets.UTF_8); + action = URLDecoder.decode(urlMatcher.group(2), StandardCharsets.UTF_8); - if (urlMatcher.group(3) == null) { - value = null; - } else { - value = URLDecoder.decode(urlMatcher.group(3), CHARSET); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Could not decode request params", e); + if (urlMatcher.group(3) == null) { + value = null; + } else { + value = URLDecoder.decode(urlMatcher.group(3), StandardCharsets.UTF_8); } logger.debug("Action request for device {}: [{}] [{}]", deviceId, action, value); diff --git a/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceHistoryHandler.java b/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceHistoryHandler.java index 47576499e..d8bbbb80d 100644 --- a/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceHistoryHandler.java +++ b/bundles/org.openhab.io.imperihome/src/main/java/org/openhab/io/imperihome/internal/handler/DeviceHistoryHandler.java @@ -12,8 +12,8 @@ */ package org.openhab.io.imperihome.internal.handler; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -45,8 +45,6 @@ import org.slf4j.LoggerFactory; */ public class DeviceHistoryHandler { - private static final String CHARSET = "UTF-8"; - private final Logger logger = LoggerFactory.getLogger(DeviceHistoryHandler.class); private final DeviceRegistry deviceRegistry; @@ -61,11 +59,11 @@ public class DeviceHistoryHandler { String deviceId, field; long start, end; try { - deviceId = URLDecoder.decode(urlMatcher.group(1), CHARSET); - field = URLDecoder.decode(urlMatcher.group(2), CHARSET); + deviceId = URLDecoder.decode(urlMatcher.group(1), StandardCharsets.UTF_8); + field = URLDecoder.decode(urlMatcher.group(2), StandardCharsets.UTF_8); start = Long.parseLong(urlMatcher.group(3)); end = Long.parseLong(urlMatcher.group(4)); - } catch (UnsupportedEncodingException | NumberFormatException e) { + } catch (NumberFormatException e) { throw new RuntimeException("Could not decode request params", e); } diff --git a/bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/NeeoUtil.java b/bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/NeeoUtil.java index db872cf80..80b4ea728 100644 --- a/bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/NeeoUtil.java +++ b/bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/NeeoUtil.java @@ -14,7 +14,6 @@ package org.openhab.io.neeo.internal; import java.io.IOException; import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -158,16 +157,7 @@ public class NeeoUtil { if (s == null) { return ""; } - - String result = null; - try { - result = URLDecoder.decode(s, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - // This exception should never occur. - result = s; - } - - return result; + return URLDecoder.decode(s, StandardCharsets.UTF_8); } /** @@ -180,18 +170,8 @@ public class NeeoUtil { */ public static String encodeURIComponent(String s) { requireNotEmpty(s, "s cannot be null or empty"); - String result = null; - - try { - result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!") - .replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")") - .replaceAll("\\%7E", "~"); - } catch (UnsupportedEncodingException e) { - // This exception should never occur. - result = s; - } - - return result; + return URLEncoder.encode(s, StandardCharsets.UTF_8).replaceAll("\\+", "%20").replaceAll("\\%21", "!") + .replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~"); } /** diff --git a/bundles/org.openhab.transform.javascript/src/main/java/org/openhab/transform/javascript/internal/JavaScriptTransformationService.java b/bundles/org.openhab.transform.javascript/src/main/java/org/openhab/transform/javascript/internal/JavaScriptTransformationService.java index 2294d11bf..c9dabf31e 100644 --- a/bundles/org.openhab.transform.javascript/src/main/java/org/openhab/transform/javascript/internal/JavaScriptTransformationService.java +++ b/bundles/org.openhab.transform.javascript/src/main/java/org/openhab/transform/javascript/internal/JavaScriptTransformationService.java @@ -14,9 +14,9 @@ package org.openhab.transform.javascript.internal; import java.io.File; import java.io.FilenameFilter; -import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -107,7 +107,7 @@ public class JavaScriptTransformationService implements TransformationService, C filename = parts[0]; try { vars = splitQuery(parts[1]); - } catch (UnsupportedEncodingException e) { + } catch (IllegalArgumentException e) { throw new TransformationException("Illegal filename syntax"); } if (isReservedWordUsed(vars)) { @@ -142,16 +142,17 @@ public class JavaScriptTransformationService implements TransformationService, C return false; } - private Map splitQuery(@Nullable String query) throws UnsupportedEncodingException { + private Map splitQuery(@Nullable String query) throws IllegalArgumentException { Map result = new LinkedHashMap<>(); if (query != null) { String[] pairs = query.split("&"); for (String pair : pairs) { String[] keyval = pair.split("="); if (keyval.length != 2) { - throw new UnsupportedEncodingException(); + throw new IllegalArgumentException(); } else { - result.put(URLDecoder.decode(keyval[0], "UTF-8"), URLDecoder.decode(keyval[1], "UTF-8")); + result.put(URLDecoder.decode(keyval[0], StandardCharsets.UTF_8), + URLDecoder.decode(keyval[1], StandardCharsets.UTF_8)); } } } diff --git a/bundles/org.openhab.voice.voicerss/src/main/java/org/openhab/voice/voicerss/internal/cloudapi/VoiceRSSCloudImpl.java b/bundles/org.openhab.voice.voicerss/src/main/java/org/openhab/voice/voicerss/internal/cloudapi/VoiceRSSCloudImpl.java index 8d50281b9..7ad300e39 100644 --- a/bundles/org.openhab.voice.voicerss/src/main/java/org/openhab/voice/voicerss/internal/cloudapi/VoiceRSSCloudImpl.java +++ b/bundles/org.openhab.voice.voicerss/src/main/java/org/openhab/voice/voicerss/internal/cloudapi/VoiceRSSCloudImpl.java @@ -16,11 +16,11 @@ import static java.util.stream.Collectors.toSet; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -255,14 +255,7 @@ public class VoiceRSSCloudImpl implements VoiceRSSCloudAPI { * It is in package scope to be accessed by tests. */ private String createURL(String apiKey, String text, String locale, String voice, String audioFormat) { - String encodedMsg; - try { - encodedMsg = URLEncoder.encode(text, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - logger.error("UnsupportedEncodingException for UTF-8 MUST NEVER HAPPEN! Check your JVM configuration!", ex); - // fall through and use msg un-encoded - encodedMsg = text; - } + String encodedMsg = URLEncoder.encode(text, StandardCharsets.UTF_8); String url = "http://api.voicerss.org/?key=" + apiKey + "&hl=" + locale + "&c=" + audioFormat; if (!DEFAULT_VOICE.equals(voice)) { url += "&v=" + voice; diff --git a/itests/org.openhab.binding.nest.tests/src/main/java/org/openhab/binding/nest/internal/wwn/dto/WWNDataUtil.java b/itests/org.openhab.binding.nest.tests/src/main/java/org/openhab/binding/nest/internal/wwn/dto/WWNDataUtil.java index 53e5eb129..7622bbd7a 100644 --- a/itests/org.openhab.binding.nest.tests/src/main/java/org/openhab/binding/nest/internal/wwn/dto/WWNDataUtil.java +++ b/itests/org.openhab.binding.nest.tests/src/main/java/org/openhab/binding/nest/internal/wwn/dto/WWNDataUtil.java @@ -17,7 +17,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; import javax.measure.Unit; @@ -65,11 +65,11 @@ public final class WWNDataUtil { // Hidden utility class constructor } - public static Reader openDataReader(String fileName) throws UnsupportedEncodingException { + public static Reader openDataReader(String fileName) { String packagePath = (WWNDataUtil.class.getPackage().getName()).replaceAll("\\.", "/"); String filePath = "/" + packagePath + "/" + fileName; InputStream inputStream = WWNDataUtil.class.getClassLoader().getResourceAsStream(filePath); - return new InputStreamReader(inputStream, "UTF-8"); + return new InputStreamReader(inputStream, StandardCharsets.UTF_8); } public static T fromJson(String fileName, Class dataClass) throws IOException {