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;
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());
}
}
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);
}
}
// 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");
*/
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;
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);
}
}
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.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;
}
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) {
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;
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 {
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;
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);
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;
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();
}
*/
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;
}
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) {
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;
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());
}
}
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());
}
}
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;
}
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 {
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;
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;
// 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);
}
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);
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),
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;
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));
}
}
}
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;
}
}
- 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
}
public void dispose() {
- try {
- httpService.unregister(servletUrl());
- } catch (UnsupportedEncodingException e) {
- logger.warn("Unregistration of servlet failed", e);
- }
+ httpService.unregister(servletUrl());
}
}
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;
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";
* 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", "*/*");
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");
*/
package org.openhab.binding.hccrubbishcollection.internal;
-import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
/**
* Create a new API class.
- *
+ *
* @param httpClient The common http client provided from openHAB.
* @param address The address of the premises.
*/
/**
* 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);
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)";
/**
* Returns the last request status.
- *
+ *
* @return ThingStatusDetail The openHAB error type.
*/
public ThingStatusDetail getErrorDetail() {
/**
* Gets the error, if occurred.
- *
+ *
* @return String The error message.
*/
public String getErrorDetailMessage() {
/**
* The collection week.
- *
+ *
* @return Integer The week number.
*/
public @Nullable Integer getCollectionWeek() {
/**
* Gets the collection day of week.
- *
+ *
* @return Integer The day of the week. 1 = Monday.
*/
public @Nullable Integer getDay() {
/**
* The upcoming recycling collection date.
- *
+ *
* @return ZonedDateTime
*/
public @Nullable ZonedDateTime getRecyclingDate() {
/**
* The upcoming general rubbish collection date.
- *
+ *
* @return ZonedDateTime
*/
public @Nullable ZonedDateTime getGeneralDate() {
*/
package org.openhab.binding.heos.internal.json;
-import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
}
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);
}
}
*/
package org.openhab.binding.heos.internal.resources;
-import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
}
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", "@");
}
}
*/
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;
* @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";
/**
* 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;
}
}
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;
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;
/**
* 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);
/**
* 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");
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);
}
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);
}
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;
/**
* 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();
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());
}
*/
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;
}
@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));
}
}
*/
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;
* @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() {
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;
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);
}
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;
}
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) {
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;
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;
*/
package org.openhab.binding.loxone.internal.security;
-import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
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());
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/[^/]*/[^/]*/", "");
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;
}
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);
*/
package org.openhab.binding.magentatv.internal;
-import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Set;
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";
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;
*/
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);
}
return sb.toString();
- } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
+ } catch (NoSuchAlgorithmException e) {
return "";
}
}
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;
} finally {
// send response
if (response != null) {
- response.setCharacterEncoding(UTF_8);
+ response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.getWriter().write("");
}
}
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;
}
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);
}
}
*/
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;
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) {
*/
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;
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);
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;
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());
}
}
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();
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;
@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> T fromJson(String fileName, Class<T> dataClass) throws IOException {
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;
/**
* authenticates with the Nibe Uplink WEB interface
- *
- * @throws UnsupportedEncodingException
*/
private synchronized void authenticate() {
setAuthenticated(false);
*/
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;
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]);
}
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;
* @author Michael Lobstein - Cleanup for RadioThermostat
*
*/
-
@NonNullByDefault
@Component(service = DiscoveryService.class, configurationPid = "discovery.radiothermostat")
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");
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 {
*/
package org.openhab.binding.robonect.internal.model.cmd;
-import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* The command allows to set or retrieve the mower name.
- *
+ *
* @author Marco Meyer - Initial contribution
*/
public class NameCommand implements Command {
/**
* sets the mower name.
- *
+ *
* @param newName - the mower name.
* @return - the command instance.
*/
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);
}
}
}
import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
-import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
}
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() {
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;
* 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
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;
/**
* authenticates with the Solaredge WEB interface
- *
- * @throws UnsupportedEncodingException
*/
private synchronized void authenticate() {
setAuthenticated(false);
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;
}
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() {
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;
// 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;
}
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
import static org.openhab.binding.touchwand.internal.TouchWandBindingConstants.*;
-import java.io.UnsupportedEncodingException;
import java.net.CookieManager;
import java.net.MalformedURLException;
import java.net.URL;
}
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");
}
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;
*/
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<Boolean> settingURI = isSettingURI;
- if (settingURI != null) {
- settingURI.complete(false);
- }
- isSettingURI = new CompletableFuture<Boolean>(); // 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<Boolean> settingURI = isSettingURI;
+ if (settingURI != null) {
+ settingURI.complete(false);
}
- } catch (UnsupportedEncodingException ignore) {
- uri = URI;
+ isSettingURI = new CompletableFuture<Boolean>(); // 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<String, String> inputs = new HashMap<>();
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)) {
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);
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;
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;
* @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;
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;
*/
package org.openhab.binding.zoneminder.internal.handler;
-import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
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);
}
*/
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;
*/
public class DeviceActionHandler {
- private static final String CHARSET = "UTF-8";
-
private final Logger logger = LoggerFactory.getLogger(DeviceActionHandler.class);
private final DeviceRegistry deviceRegistry;
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);
*/
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;
*/
public class DeviceHistoryHandler {
- private static final String CHARSET = "UTF-8";
-
private final Logger logger = LoggerFactory.getLogger(DeviceHistoryHandler.class);
private final DeviceRegistry deviceRegistry;
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);
}
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;
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);
}
/**
*/
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", "~");
}
/**
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;
filename = parts[0];
try {
vars = splitQuery(parts[1]);
- } catch (UnsupportedEncodingException e) {
+ } catch (IllegalArgumentException e) {
throw new TransformationException("Illegal filename syntax");
}
if (isReservedWordUsed(vars)) {
return false;
}
- private Map<String, String> splitQuery(@Nullable String query) throws UnsupportedEncodingException {
+ private Map<String, String> splitQuery(@Nullable String query) throws IllegalArgumentException {
Map<String, String> 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));
}
}
}
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;
* 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;
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;
// 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> T fromJson(String fileName, Class<T> dataClass) throws IOException {