]> git.basschouten.com Git - openhab-addons.git/commitdiff
[miio] Java style cleanup (#15610)
authorMarcel <marcel@verpaalen.com>
Tue, 19 Sep 2023 20:53:50 +0000 (22:53 +0200)
committerGitHub <noreply@github.com>
Tue, 19 Sep 2023 20:53:50 +0000 (22:53 +0200)
Introducing non-breaking improvements from #15520
- Java style array syntax
- remove redundant modifiers
- always move String constants to left side in comparisons
- multiline strings

Signed-off-by: Marcel Verpaalen <marcel@verpaalen.com>
Co-authored-by: Holger Friedrich <mail@holger-friedrich.de>
12 files changed:
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/MiIoCrypto.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/Utils.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/cloud/CloudConnector.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/cloud/MiCloudConnector.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/handler/MiIoAbstractHandler.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/handler/MiIoVacuumHandler.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/miot/MiotParser.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/robot/RRMapDraw.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/robot/RRMapDrawOptions.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/transport/MiIoAsyncCommunication.java
bundles/org.openhab.binding.miio/src/test/java/org/openhab/binding/miio/internal/ReadmeHelper.java
bundles/org.openhab.binding.miio/src/test/java/org/openhab/binding/miio/internal/RoboMapViewer.java

index 3e5e57a4add2946b07ea840bd48fdd72cd1a6943..f162fc364333502568f8aebb0a9c5ff5fb61b618 100644 (file)
@@ -62,8 +62,7 @@ public class MiIoCrypto {
             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
             SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
             cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector);
-            byte[] encrypted = cipher.doFinal(cipherText);
-            return encrypted;
+            return cipher.doFinal(cipherText);
         } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                 | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
             throw new MiIoCryptoException(e.getMessage(), e);
@@ -80,8 +79,7 @@ public class MiIoCrypto {
             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
             SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
             cipher.init(Cipher.DECRYPT_MODE, keySpec, vector);
-            byte[] crypted = cipher.doFinal(cipherText);
-            return (crypted);
+            return cipher.doFinal(cipherText);
         } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                 | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
             throw new MiIoCryptoException(e.getMessage(), e);
index 42189dedfa2cc3b28e08cc13d3b88c9a8952a0e2..ad8aabb485fb9c0dc595ddac66291d0b0cd7565e 100644 (file)
@@ -91,10 +91,9 @@ public final class Utils {
 
     public static String obfuscateToken(String tokenString) {
         if (tokenString.length() > 8) {
-            String tokenText = tokenString.substring(0, 8)
+            return tokenString.substring(0, 8)
                     .concat((tokenString.length() < 24) ? tokenString.substring(8).replaceAll(".", "X")
                             : tokenString.substring(8, 24).replaceAll(".", "X").concat(tokenString.substring(24)));
-            return tokenText;
         } else {
             return tokenString;
         }
index a087591d9ad5bd297d0df32990d0938b45a57f12..c6d8758402177e842ec9efef7765230553d7efb6 100644 (file)
@@ -46,7 +46,7 @@ public class CloudConnector {
 
     private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60);
 
-    private static enum DeviceListState {
+    private enum DeviceListState {
         FAILED,
         STARTING,
         REFRESHING,
index 302de9d21979d0f518f099b3b3ddb06f26a21114..d2700081dd296fe31b0837d5f892170650d3a0d8 100644 (file)
@@ -131,7 +131,7 @@ public class MiCloudConnector {
     }
 
     private String getApiUrl(String country) {
-        return "https://" + (country.trim().equalsIgnoreCase("cn") ? "" : country.trim().toLowerCase() + ".")
+        return "https://" + ("cn".equalsIgnoreCase(country.trim()) ? "" : country.trim().toLowerCase() + ".")
                 + "api.io.mi.com/app";
     }
 
@@ -180,8 +180,7 @@ public class MiCloudConnector {
     }
 
     public String getDeviceStatus(String device, String country) throws MiCloudException {
-        final String response = request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}");
-        return response;
+        return request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}");
     }
 
     public String sendRPCCommand(String device, String country, String command) throws MiCloudException {
@@ -199,8 +198,7 @@ public class MiCloudConnector {
             logger.debug("{}", err);
             throw new MiCloudException(err, e);
         }
-        final String response = request("/home/rpc/" + id, country, command);
-        return response;
+        return request("/home/rpc/" + id, country, command);
     }
 
     public List<CloudDeviceDTO> getDevices(String country) {
@@ -412,7 +410,7 @@ public class MiCloudConnector {
         try {
             JsonElement resp = JsonParser.parseString(parseJson(content));
             CloudLogin1DTO jsonResp = GSON.fromJson(resp, CloudLogin1DTO.class);
-            final String sign = jsonResp.getSign();
+            final String sign = jsonResp != null ? jsonResp.getSign() : null;
             if (sign != null && !sign.isBlank()) {
                 logger.trace("Xiaomi Login step 1 sign = {}", sign);
                 return sign;
@@ -476,8 +474,14 @@ public class MiCloudConnector {
         if (0 != jsonResp.getSecurityStatus()) {
             logger.debug("Xiaomi Cloud Step2 response: {}", parseJson(content2));
             logger.debug(
-                    "Xiaomi Login code: {} \r\nSecurityStatus: {}\r\nPwd code: {}\r\nLocation logon URL: {}\r\nIn case of login issues check userId/password details are correct.\r\n"
-                            + "If login details are correct, try to logon using browser from the openHAB ip using the browser. Alternatively try to complete logon with above URL.",
+                    """
+                            Xiaomi Login code: {}
+                            SecurityStatus: {}
+                            Pwd code: {}
+                            Location logon URL: {}
+                            In case of login issues check userId/password details are correct.
+                            If login details are correct, try to logon using browser from the openHAB ip using the browser. Alternatively try to complete logon with above URL.\
+                            """,
                     jsonResp.getCode(), jsonResp.getSecurityStatus(), jsonResp.getPwd(), jsonResp.getLocation());
         }
         if (logger.isTraceEnabled()) {
index 094fa14dcbfecd1c0758c183d212dff9b7888ef0..342c0b43679ba93a9c77a15be6fde3c8e3bd372f 100644 (file)
@@ -314,7 +314,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
             final MiIoAsyncCommunication connection = getConnection();
             return (connection != null) ? connection.queueCommand(command, params, cloudServer, sender) : 0;
         } catch (MiIoCryptoException | IOException e) {
-            logger.debug("Command {} for {} failed (type: {}): {}", command.toString(), getThing().getUID(),
+            logger.debug("Command {} for {} failed (type: {}): {}", command, getThing().getUID(),
                     getThing().getThingTypeUID(), e.getLocalizedMessage());
             disconnected(e.getMessage());
         }
@@ -327,7 +327,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
         // simple and only have the option for cloud or direct.
         final MiIoBindingConfiguration configuration = this.configuration;
         if (configuration != null) {
-            return configuration.communication.equals("cloud") ? cloudServer : "";
+            return "cloud".equals(configuration.communication) ? cloudServer : "";
         }
         return "";
     }
@@ -526,7 +526,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
             return cmd;
         }
         String returnCmd = cmd.replace("\"$", "$").replace("$\"", "$");
-        String cmdParts[] = cmd.split("\\$");
+        String[] cmdParts = cmd.split("\\$");
         if (logger.isTraceEnabled()) {
             logger.debug("processSubstitutions {} ", cmd);
             for (Entry<String, Object> e : deviceVariables.entrySet()) {
index ca5f59965c788e30cfa7c7c37ad1e266a9543d80..193e7471112568a3e76c304c12e87248c282dda1 100644 (file)
@@ -213,13 +213,13 @@ public class MiIoVacuumHandler extends MiIoAbstractHandler {
             }
         }
         if (channelUID.getId().equals(CHANNEL_CONTROL)) {
-            if (command.toString().equals("vacuum")) {
+            if ("vacuum".equals(command.toString())) {
                 sendCommand(MiIoCommand.START_VACUUM);
-            } else if (command.toString().equals("spot")) {
+            } else if ("spot".equals(command.toString())) {
                 sendCommand(MiIoCommand.START_SPOT);
-            } else if (command.toString().equals("pause")) {
+            } else if ("pause".equals(command.toString())) {
                 sendCommand(MiIoCommand.PAUSE);
-            } else if (command.toString().equals("dock")) {
+            } else if ("dock".equals(command.toString())) {
                 sendCommand(MiIoCommand.STOP_VACUUM);
                 miIoScheduler.schedule(() -> {
                     sendCommand(MiIoCommand.CHARGE);
index b478396d281e5e0c678e4a8c45b15c4023386580..d12828b686d19d1201da5d2b33be1e5faf5c6265 100644 (file)
@@ -241,7 +241,7 @@ public class MiotParser {
                         }
                         miIoBasicChannel.setRefresh(property.access.contains("read"));
                         // add option values
-                        if (property.valueList != null && property.valueList.size() > 0) {
+                        if (property.valueList != null && !property.valueList.isEmpty()) {
                             StateDescriptionDTO stateDescription = miIoBasicChannel.getStateDescription();
                             if (stateDescription == null) {
                                 stateDescription = new StateDescriptionDTO();
index b44f937429dd489ff5f19c6c68f536f09b1e8038..631742ee268840fbfae3253eb5366a3a5faaa053 100644 (file)
@@ -281,7 +281,6 @@ public class RRMapDraw {
                 g2d.draw(noGo);
             }
         }
-        ;
     }
 
     private void drawWalls(Graphics2D g2d, float scale) {
@@ -369,8 +368,8 @@ public class RRMapDraw {
         if (!(x == 0 && y == 0)) {
             g2d.setStroke(new BasicStroke());
             g2d.setColor(Color.YELLOW);
-            int x3[] = { (int) x, (int) (x - 2 * scale), (int) (x + 2 * scale) };
-            int y3[] = { (int) y, (int) (y - 5 * scale), (int) (y - 5 * scale) };
+            int[] x3 = { (int) x, (int) (x - 2 * scale), (int) (x + 2 * scale) };
+            int[] y3 = { (int) y, (int) (y - 5 * scale), (int) (y - 5 * scale) };
             g2d.fill(new Polygon(x3, y3, 3));
         }
     }
index 0ea6ddfcca557858234dea178e2f2c827a084d0d..f5865541e53a2e7a2a6bf705255d464e172e4f92 100644 (file)
@@ -93,9 +93,8 @@ public class RRMapDrawOptions {
                         throw new JsonParseException("missing json text");
                     }
                     JsonObject colorSave = json.getAsJsonObject();
-                    Color color = new Color(colorSave.get("red").getAsInt(), colorSave.get("green").getAsInt(),
+                    return new Color(colorSave.get("red").getAsInt(), colorSave.get("green").getAsInt(),
                             colorSave.get("blue").getAsInt(), colorSave.get("alpha").getAsInt());
-                    return color;
                 }
             }).create();
 
@@ -301,8 +300,7 @@ public class RRMapDrawOptions {
 
     public static RRMapDrawOptions getOptionsFromFile(String fileName, Logger logger) {
         try {
-            RRMapDrawOptions options = GSON.fromJson(new FileReader(fileName), RRMapDrawOptions.class);
-            return options;
+            return GSON.fromJson(new FileReader(fileName), RRMapDrawOptions.class);
         } catch (FileNotFoundException e) {
             logger.debug("Vacuum map draw options file {} not found. Using defaults", fileName);
             return new RRMapDrawOptions();
index d64257418bbdb8308db445156a5683de64f6b8a5..1a2cc0f0a0bf6f64d736590b365d6c627013c927 100644 (file)
@@ -415,9 +415,8 @@ public class MiIoAsyncCommunication {
                 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
             }
             clientSocket.receive(receivePacket);
-            byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
+            return Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
                     receivePacket.getOffset() + receivePacket.getLength());
-            return response;
         } catch (SocketTimeoutException e) {
             logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
             needPing = true;
index 97815c20dd469aa3bdc7a9d9426e02800227a0f6..7687d86ea10a5ffc43c189b73509aedceb791cb7 100644 (file)
@@ -140,7 +140,7 @@ public class ReadmeHelper {
                 "|------------------------------------|------------------|------------------------|--------------|------------|\n");
 
         Arrays.asList(MiIoDevices.values()).forEach(device -> {
-            if (!device.getModel().equals("unknown")) {
+            if (!"unknown".equals(device.getModel())) {
                 String link = device.getModel().replace(".", "-");
                 boolean isSupported = device.getThingType().equals(MiIoBindingConstants.THING_TYPE_UNSUPPORTED);
                 Boolean experimental = false;
index 76217ec2dd34d283307d61928d78108dbaac4d1a..47c258c5654d4f79b7cfee3cedf9dea64f33907a 100644 (file)
@@ -76,13 +76,13 @@ public class RoboMapViewer extends JFrame {
     private static final long serialVersionUID = 2623447051590306992L;
 
     @Disabled
-    public static void main(String args[]) {
+    public static void main(String[] args) {
         System.setProperty("swing.defaultlaf", "javax.swing.plaf.metal.MetalLookAndFeel");
         RoboMapViewer vc = new RoboMapViewer(args);
         vc.setVisible(true);
     }
 
-    public RoboMapViewer(String args[]) {
+    public RoboMapViewer(String[] args) {
         super(TITLE);
         parent = this;
         setSize(500, 600);
@@ -319,9 +319,8 @@ public class RoboMapViewer extends JFrame {
     }
 
     protected boolean isRRFile(File fileEntry) {
-        boolean isRRFile = fileEntry.getName().toLowerCase().endsWith(".rrmap")
+        return fileEntry.getName().toLowerCase().endsWith(".rrmap")
                 || fileEntry.getName().toLowerCase().endsWith(".gz");
-        return isRRFile;
     }
 
     private void loadFirstFile() {