[miio] Java style cleanup (#15610)

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>
This commit is contained in:
Marcel 2023-09-19 22:53:50 +02:00 committed by GitHub
parent 14cfeb0996
commit bf1aa3deb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 33 additions and 37 deletions

View File

@ -62,8 +62,7 @@ public class MiIoCrypto {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector); cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector);
byte[] encrypted = cipher.doFinal(cipherText); return cipher.doFinal(cipherText);
return encrypted;
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
throw new MiIoCryptoException(e.getMessage(), e); throw new MiIoCryptoException(e.getMessage(), e);
@ -80,8 +79,7 @@ public class MiIoCrypto {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, vector); cipher.init(Cipher.DECRYPT_MODE, keySpec, vector);
byte[] crypted = cipher.doFinal(cipherText); return cipher.doFinal(cipherText);
return (crypted);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
throw new MiIoCryptoException(e.getMessage(), e); throw new MiIoCryptoException(e.getMessage(), e);

View File

@ -91,10 +91,9 @@ public final class Utils {
public static String obfuscateToken(String tokenString) { public static String obfuscateToken(String tokenString) {
if (tokenString.length() > 8) { if (tokenString.length() > 8) {
String tokenText = tokenString.substring(0, 8) return tokenString.substring(0, 8)
.concat((tokenString.length() < 24) ? tokenString.substring(8).replaceAll(".", "X") .concat((tokenString.length() < 24) ? tokenString.substring(8).replaceAll(".", "X")
: tokenString.substring(8, 24).replaceAll(".", "X").concat(tokenString.substring(24))); : tokenString.substring(8, 24).replaceAll(".", "X").concat(tokenString.substring(24)));
return tokenText;
} else { } else {
return tokenString; return tokenString;
} }

View File

@ -46,7 +46,7 @@ public class CloudConnector {
private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60); private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60);
private static enum DeviceListState { private enum DeviceListState {
FAILED, FAILED,
STARTING, STARTING,
REFRESHING, REFRESHING,

View File

@ -131,7 +131,7 @@ public class MiCloudConnector {
} }
private String getApiUrl(String country) { 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"; + "api.io.mi.com/app";
} }
@ -180,8 +180,7 @@ public class MiCloudConnector {
} }
public String getDeviceStatus(String device, String country) throws MiCloudException { public String getDeviceStatus(String device, String country) throws MiCloudException {
final String response = request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}"); return request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}");
return response;
} }
public String sendRPCCommand(String device, String country, String command) throws MiCloudException { public String sendRPCCommand(String device, String country, String command) throws MiCloudException {
@ -199,8 +198,7 @@ public class MiCloudConnector {
logger.debug("{}", err); logger.debug("{}", err);
throw new MiCloudException(err, e); throw new MiCloudException(err, e);
} }
final String response = request("/home/rpc/" + id, country, command); return request("/home/rpc/" + id, country, command);
return response;
} }
public List<CloudDeviceDTO> getDevices(String country) { public List<CloudDeviceDTO> getDevices(String country) {
@ -412,7 +410,7 @@ public class MiCloudConnector {
try { try {
JsonElement resp = JsonParser.parseString(parseJson(content)); JsonElement resp = JsonParser.parseString(parseJson(content));
CloudLogin1DTO jsonResp = GSON.fromJson(resp, CloudLogin1DTO.class); 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()) { if (sign != null && !sign.isBlank()) {
logger.trace("Xiaomi Login step 1 sign = {}", sign); logger.trace("Xiaomi Login step 1 sign = {}", sign);
return sign; return sign;
@ -476,8 +474,14 @@ public class MiCloudConnector {
if (0 != jsonResp.getSecurityStatus()) { if (0 != jsonResp.getSecurityStatus()) {
logger.debug("Xiaomi Cloud Step2 response: {}", parseJson(content2)); logger.debug("Xiaomi Cloud Step2 response: {}", parseJson(content2));
logger.debug( 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()); jsonResp.getCode(), jsonResp.getSecurityStatus(), jsonResp.getPwd(), jsonResp.getLocation());
} }
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {

View File

@ -314,7 +314,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
final MiIoAsyncCommunication connection = getConnection(); final MiIoAsyncCommunication connection = getConnection();
return (connection != null) ? connection.queueCommand(command, params, cloudServer, sender) : 0; return (connection != null) ? connection.queueCommand(command, params, cloudServer, sender) : 0;
} catch (MiIoCryptoException | IOException e) { } 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()); getThing().getThingTypeUID(), e.getLocalizedMessage());
disconnected(e.getMessage()); 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. // simple and only have the option for cloud or direct.
final MiIoBindingConfiguration configuration = this.configuration; final MiIoBindingConfiguration configuration = this.configuration;
if (configuration != null) { if (configuration != null) {
return configuration.communication.equals("cloud") ? cloudServer : ""; return "cloud".equals(configuration.communication) ? cloudServer : "";
} }
return ""; return "";
} }
@ -526,7 +526,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
return cmd; return cmd;
} }
String returnCmd = cmd.replace("\"$", "$").replace("$\"", "$"); String returnCmd = cmd.replace("\"$", "$").replace("$\"", "$");
String cmdParts[] = cmd.split("\\$"); String[] cmdParts = cmd.split("\\$");
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.debug("processSubstitutions {} ", cmd); logger.debug("processSubstitutions {} ", cmd);
for (Entry<String, Object> e : deviceVariables.entrySet()) { for (Entry<String, Object> e : deviceVariables.entrySet()) {

View File

@ -213,13 +213,13 @@ public class MiIoVacuumHandler extends MiIoAbstractHandler {
} }
} }
if (channelUID.getId().equals(CHANNEL_CONTROL)) { if (channelUID.getId().equals(CHANNEL_CONTROL)) {
if (command.toString().equals("vacuum")) { if ("vacuum".equals(command.toString())) {
sendCommand(MiIoCommand.START_VACUUM); sendCommand(MiIoCommand.START_VACUUM);
} else if (command.toString().equals("spot")) { } else if ("spot".equals(command.toString())) {
sendCommand(MiIoCommand.START_SPOT); sendCommand(MiIoCommand.START_SPOT);
} else if (command.toString().equals("pause")) { } else if ("pause".equals(command.toString())) {
sendCommand(MiIoCommand.PAUSE); sendCommand(MiIoCommand.PAUSE);
} else if (command.toString().equals("dock")) { } else if ("dock".equals(command.toString())) {
sendCommand(MiIoCommand.STOP_VACUUM); sendCommand(MiIoCommand.STOP_VACUUM);
miIoScheduler.schedule(() -> { miIoScheduler.schedule(() -> {
sendCommand(MiIoCommand.CHARGE); sendCommand(MiIoCommand.CHARGE);

View File

@ -241,7 +241,7 @@ public class MiotParser {
} }
miIoBasicChannel.setRefresh(property.access.contains("read")); miIoBasicChannel.setRefresh(property.access.contains("read"));
// add option values // add option values
if (property.valueList != null && property.valueList.size() > 0) { if (property.valueList != null && !property.valueList.isEmpty()) {
StateDescriptionDTO stateDescription = miIoBasicChannel.getStateDescription(); StateDescriptionDTO stateDescription = miIoBasicChannel.getStateDescription();
if (stateDescription == null) { if (stateDescription == null) {
stateDescription = new StateDescriptionDTO(); stateDescription = new StateDescriptionDTO();

View File

@ -281,7 +281,6 @@ public class RRMapDraw {
g2d.draw(noGo); g2d.draw(noGo);
} }
} }
;
} }
private void drawWalls(Graphics2D g2d, float scale) { private void drawWalls(Graphics2D g2d, float scale) {
@ -369,8 +368,8 @@ public class RRMapDraw {
if (!(x == 0 && y == 0)) { if (!(x == 0 && y == 0)) {
g2d.setStroke(new BasicStroke()); g2d.setStroke(new BasicStroke());
g2d.setColor(Color.YELLOW); g2d.setColor(Color.YELLOW);
int x3[] = { (int) x, (int) (x - 2 * scale), (int) (x + 2 * 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) }; int[] y3 = { (int) y, (int) (y - 5 * scale), (int) (y - 5 * scale) };
g2d.fill(new Polygon(x3, y3, 3)); g2d.fill(new Polygon(x3, y3, 3));
} }
} }

View File

@ -93,9 +93,8 @@ public class RRMapDrawOptions {
throw new JsonParseException("missing json text"); throw new JsonParseException("missing json text");
} }
JsonObject colorSave = json.getAsJsonObject(); 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()); colorSave.get("blue").getAsInt(), colorSave.get("alpha").getAsInt());
return color;
} }
}).create(); }).create();
@ -301,8 +300,7 @@ public class RRMapDrawOptions {
public static RRMapDrawOptions getOptionsFromFile(String fileName, Logger logger) { public static RRMapDrawOptions getOptionsFromFile(String fileName, Logger logger) {
try { try {
RRMapDrawOptions options = GSON.fromJson(new FileReader(fileName), RRMapDrawOptions.class); return GSON.fromJson(new FileReader(fileName), RRMapDrawOptions.class);
return options;
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
logger.debug("Vacuum map draw options file {} not found. Using defaults", fileName); logger.debug("Vacuum map draw options file {} not found. Using defaults", fileName);
return new RRMapDrawOptions(); return new RRMapDrawOptions();

View File

@ -415,9 +415,8 @@ public class MiIoAsyncCommunication {
sendPacket.setData(new byte[MSG_BUFFER_SIZE]); sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
} }
clientSocket.receive(receivePacket); clientSocket.receive(receivePacket);
byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(), return Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
receivePacket.getOffset() + receivePacket.getLength()); receivePacket.getOffset() + receivePacket.getLength());
return response;
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage()); logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
needPing = true; needPing = true;

View File

@ -140,7 +140,7 @@ public class ReadmeHelper {
"|------------------------------------|------------------|------------------------|--------------|------------|\n"); "|------------------------------------|------------------|------------------------|--------------|------------|\n");
Arrays.asList(MiIoDevices.values()).forEach(device -> { Arrays.asList(MiIoDevices.values()).forEach(device -> {
if (!device.getModel().equals("unknown")) { if (!"unknown".equals(device.getModel())) {
String link = device.getModel().replace(".", "-"); String link = device.getModel().replace(".", "-");
boolean isSupported = device.getThingType().equals(MiIoBindingConstants.THING_TYPE_UNSUPPORTED); boolean isSupported = device.getThingType().equals(MiIoBindingConstants.THING_TYPE_UNSUPPORTED);
Boolean experimental = false; Boolean experimental = false;

View File

@ -76,13 +76,13 @@ public class RoboMapViewer extends JFrame {
private static final long serialVersionUID = 2623447051590306992L; private static final long serialVersionUID = 2623447051590306992L;
@Disabled @Disabled
public static void main(String args[]) { public static void main(String[] args) {
System.setProperty("swing.defaultlaf", "javax.swing.plaf.metal.MetalLookAndFeel"); System.setProperty("swing.defaultlaf", "javax.swing.plaf.metal.MetalLookAndFeel");
RoboMapViewer vc = new RoboMapViewer(args); RoboMapViewer vc = new RoboMapViewer(args);
vc.setVisible(true); vc.setVisible(true);
} }
public RoboMapViewer(String args[]) { public RoboMapViewer(String[] args) {
super(TITLE); super(TITLE);
parent = this; parent = this;
setSize(500, 600); setSize(500, 600);
@ -319,9 +319,8 @@ public class RoboMapViewer extends JFrame {
} }
protected boolean isRRFile(File fileEntry) { protected boolean isRRFile(File fileEntry) {
boolean isRRFile = fileEntry.getName().toLowerCase().endsWith(".rrmap") return fileEntry.getName().toLowerCase().endsWith(".rrmap")
|| fileEntry.getName().toLowerCase().endsWith(".gz"); || fileEntry.getName().toLowerCase().endsWith(".gz");
return isRRFile;
} }
private void loadFirstFile() { private void loadFirstFile() {