Skip to content

Commit

Permalink
Avoid UnsupportedEncodingException & use const from StandardCharsets
Browse files Browse the repository at this point in the history
Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
  • Loading branch information
cweitkamp committed Jan 3, 2022
1 parent 3884b37 commit 37056c7
Show file tree
Hide file tree
Showing 52 changed files with 180 additions and 415 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
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;
Expand Down Expand Up @@ -88,11 +87,11 @@ public AccountServlet(HttpService httpService, String id, AccountHandler account
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());
}
}
Expand Down Expand Up @@ -340,12 +339,7 @@ public Map<String, String> getQueryMap(@Nullable String query) {
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);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -60,12 +60,10 @@ public DiscoveryListener() throws IOException, SocketException {
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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
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;
Expand Down Expand Up @@ -611,13 +611,7 @@ public void send(String command) {
}

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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
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;
Expand Down Expand Up @@ -172,22 +171,17 @@ protected void internalSendCommand(String command) {
return;
}

try {
String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName());
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());
}
}
});
String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset());
logger.trace("Calling url {}", url);

} catch (UnsupportedEncodingException e) {
logger.warn("Error sending command", e);
}
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());
}
}
});
}

private void updateMain() throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public void openConnection() {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
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;
Expand Down Expand Up @@ -268,10 +267,10 @@ public boolean performThermostatUpdate(ThermostatUpdateRequestDTO request) {
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();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -200,17 +200,9 @@ private boolean authenticate(String credentials, String grantType) {
}

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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

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;
Expand Down Expand Up @@ -92,12 +91,12 @@ public int getApiKeyLimitRemaining() {
public synchronized List<FoobotDevice> 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<FoobotDevice> 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());
}
}
Expand All @@ -112,11 +111,11 @@ public synchronized List<FoobotDevice> getAssociatedDevices(String username) thr
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());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
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;
Expand Down Expand Up @@ -470,11 +469,7 @@ private <T extends FreeboxResponse<F>, F> F evaluateJsonReesponse(String jsonRes
}

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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
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;
Expand All @@ -29,6 +28,7 @@
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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -578,7 +575,8 @@ private void writeSerialToDevice(RequestMessage requestMessage) throws IOExcepti
}

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);
Expand Down Expand Up @@ -912,14 +910,8 @@ private SerialPortReader startSerialPortReader(CommandType serialDevice, String
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),
Expand Down Expand Up @@ -1003,9 +995,6 @@ private void serialPortReader() {
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;
Expand Down Expand Up @@ -1071,13 +1060,10 @@ private void updateFeedbackChannel(byte[] buffer) {
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));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -55,8 +54,8 @@ public AccountServlet(HttpService httpService, String bridgeId, GroheOndusAccoun
}
}

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
Expand Down Expand Up @@ -130,10 +129,6 @@ protected void doDelete(@Nullable HttpServletRequest req, @Nullable HttpServletR
}

public void dispose() {
try {
httpService.unregister(servletUrl());
} catch (UnsupportedEncodingException e) {
logger.warn("Unregistration of servlet failed", e);
}
httpService.unregister(servletUrl());
}
}
Loading

0 comments on commit 37056c7

Please sign in to comment.